﻿using HookupAppForm.Draw.Models;
using HookupAppForm.Dto;
using HookupAppForm.MyUserControl;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using static HookupAppForm.Dto.ResultDto;
using static HookupAppForm.MyUserControl.UserControlBlock;

namespace HookupAppForm.Draw
{
    public partial class UC_SysLayout : UserControl
    {
        public UC_SysLayout(FormMain _main)
        {
            InitializeComponent();

            client = new APIClient(webAPI);
            //dgvTool.AllowDrop = true;
            //dgvTool.MultiSelect = false;
            //dgvTool.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            panelS.AllowDrop = true;

            panelS.SizeChanged += PanelS_SizeChanged;

            ucInst = new System.Windows.Controls.UserControl();
            Load += UC_SysLayout_Load;
            main = _main;
        }

        FormMain main;
        private string TenantId { get; set; }
        private string Token { get; set; }
        private string TenancyName { get; set; }
        private string UserName { get; set; }
        private Image currentImg { get; set; }
        private int currentX { get; set; }
        private int currentY { get; set; }
        private string webAPI = ConfigurationManager.AppSettings["WebAPI"];
        private readonly string apiSubmain = "api/services/app/HKP_Submain/";
        private readonly string apiTool = "api/services/app/HKP_Tool/";
        private readonly string apiTakeOff = "api/services/app/HKP_TakeOff/";
        private readonly string apiHDC = "api/services/app/HKP_HDC/";
        private APIClient client;
        UC_DrawShow DrawShow = null;
        List<CustomDrawInfo> MyCustomerList = new List<CustomDrawInfo>();

        private ItemsDto<HKP_SystemDto> lst_system = null;
        private ItemsDto<HKP_BlockDto> lst_block = null;
        private ItemsDto<HKP_SubmainDto> lst_guandao = null;
        private ItemsDto<HKP_TakeoffDto> lst_takeoff = null;
        private ItemsDto<HKP_ToolDto> lst_tool = null;
        private ItemsDto<HKP_CategoryDto> lst_buildfloor = null;
        private ItemsDto<HKP_ToolSysReqDto> lst_jt_sys = null;

        private ItemsDto<HKP_ToolDto> SysLst_tool = null;//按照详细系统类型筛选出来的机台

        private List<HDCReportDto> lists;
       
        

        internal HKP_TakeoffDto[] jiedian_lst_curr = null;
        private System.Windows.Media.Brush brush_paidian_used = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(128, 255, 0, 0));
        private System.Windows.Media.Brush brush_paidian_touse = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(128, 0, 255, 0));
        private System.Windows.Media.Brush brush_paidian_yellow = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 255, 0));
        private System.Windows.Media.Brush brush_paidian_blue = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 0, 0, 255));
        //当前选择的接点派到的takeoff电颜色
        private System.Windows.Media.Brush brush_paidian_NO = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 215, 151, 46));

        private readonly string apiSysReq = "api/services/app/HKP_ToolSysReq/";
        //private Dictionary<string, HKP_ToolSysReqDto[]> toolSysReqDict = new Dictionary<string, HKP_ToolSysReqDto[]>();


        #region 方法

        private double PointDist(double x1, double y1, double x2, double y2)
        {
            
               var a = x1 - x2;
            var b = y1 - y2;
            return Math.Sqrt(a * a + b * b);
        }


        ///// <summary>
        ///// 显示接点
        ///// </summary>
        ///// <param name="canvasParent"></param>
        ///// <param name="currentSys"></param>
        ///// <param name="blockId"></param>
        //private void loadChildInAreaFromCacheOld(CanvasExt canvasParent, string currentSys, long blockId)
        //{
        //    ItemsDto<HKP_TakeoffDto> res = lst_takeoff;
        //    var paidian_dist = numFitDistence.Value * 1000;

        //    if (res != null && res.result != null)
        //    {
        //        jiedian_lst_curr = res.result.items;
        //        jiedian_lst_curr = jiedian_lst_curr.Where(a => a.BlockId == blockId).ToArray();

        //        //未指定系统时，不显示接点
        //        if (!string.IsNullOrEmpty(currentSys))
        //        {
        //            jiedian_lst_curr = jiedian_lst_curr.Where(o => o.SysName == currentSys).ToArray();
        //        }
        //        else jiedian_lst_curr = new HKP_TakeoffDto[0];

        //        foreach (HKP_TakeoffDto item in jiedian_lst_curr)
        //        {
        //            var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "接点" && a.BindDataProperty == item.OutType);
        //            //如果没有指定类型的，则使用默认模型的
        //            if (typeitem == null) typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "接点");
        //            if (typeitem == null) continue;

        //            if (typeitem.EleList != null)
        //            {
        //                var EleList = typeitem.EleList;
        //                var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
        //                var x2 = (int)EleList.Max(a => Math.Min(a.LocX, a.LocX2) + a.SizeWidth);
        //                var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
        //                var y2 = (int)EleList.Max(a => Math.Min(a.LocY, a.LocY2) + a.SizeHeight);
        //                var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);

        //                //仅仅操作副本
        //                var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();

        //                #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
        //                foreach (var ele in elelist)
        //                {
        //                    ele.LocX -= rtshape.X;
        //                    ele.LocY -= rtshape.Y;
        //                    ele.LocX2 -= rtshape.X;
        //                    ele.LocY2 -= rtshape.Y;
        //                    ele.Control_1_X -= rtshape.X;
        //                    ele.Control_1_Y -= rtshape.Y;

        //                    var scaleX = DrawShow.split_arr_col.Average() * 0.7 / (double)rtshape.Width;
        //                    var scaleY = scaleX;

        //                    //var scl1 = 500 / (double)rtshape.Width;
        //                    //按照最大显示高度等比例显示
        //                    var scl2 = typeitem.ShowHeight / (double)rtshape.Height;
        //                    scaleX = scl2;
        //                    scaleY = scaleX;


        //                    ele.LocX *= scaleX;
        //                    ele.LocX2 *= scaleX;
        //                    ele.LocY *= scaleY;
        //                    ele.LocY2 *= scaleY;
        //                    ele.Control_1_X *= scaleY;
        //                    ele.Control_1_Y *= scaleY;
        //                }
        //                #endregion

        //                //图形的容器控件 
        //                var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
        //                var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
        //                var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
        //                var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));
        //                var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, xMax - xMin + 1, yMax - yMin + 1);
        //                //+边缘距离
        //                rtContainer.X += DrawShow.drawEdge_hor;
        //                rtContainer.Y += DrawShow.drawEdge_ver;
        //                //创建容器,基于父容器，父容器为区域容器
        //                rtContainer.Offset(-System.Windows.Controls.Canvas.GetLeft(canvasParent), -System.Windows.Controls.Canvas.GetTop(canvasParent));
        //                var cvNew = DrawShow.doAddDrawEleContainer_Jiedian(canvasParent, rtContainer);

        //                #region 容器的颜色  已派点的显示为红色；未派点可派点的显示为绿色；  
        //                //已派点的显示为红色；未派点可派点的显示为绿色；  
        //                //机台位置在画布中心
        //                var xcenter = DrawShow.split_arr_col.Average() / 2;
        //                var ycenter = DrawShow.split_arr_row.Average() / 2;
        //                //未派点的，可派点
        //                var canConnected = toolSysReqDict.Values.Any(a => a.Any(b =>
        //                b.OutType == item.OutType
        //                && !item.Used
        //                && item.Enabled
        //                && PointDist((double)item.X, (double)item.Y, xcenter, ycenter) <= (double)paidian_dist //指定派点距离
        //                ));
        //                //已派点
        //                var connected = toolSysReqDict.Values.Any(a => a.Any(b =>
        //                b.OutType == item.OutType
        //                && item.Used
        //                && PointDist((double)item.X, (double)item.Y, xcenter, ycenter) <= (double)paidian_dist //指定派点距离
        //                ));
        //                if (connected) cvNew.Background = brush_paidian_used;
        //                else if (canConnected) cvNew.Background = brush_paidian_touse;
        //                #endregion


        //                //列表转化
        //                item.BlockName = lst_block.result?.items?.FirstOrDefault(a => a.Id == item.BlockId)?.BlockName;
        //                item.SubmainName = lst_guandao.result?.items?.FirstOrDefault(a => a.Id == item.SubmainId)?.SubmainName;
        //                cvNew.ToolTip = new UC_Tooltip_Jiedian(item);
        //                cvNew.Data_Jiedian = item;
        //                //区域的快捷菜单
        //                container_Jiedian_Menu(cvNew, item);
        //                //子元素放入到父容器中
        //                foreach (var ele in elelist)
        //                {
        //                    DrawShow.doAddDrawEleControl(ele, cvNew);
        //                }
        //                //添加文本说明
        //                DrawShow.doAddDrawEleContainer_Desc_Jiedian(cvNew, item.TakeoffNo, typeitem.ShowHeight);

        //            }
        //        }
        //    }
        //}

        Dictionary<string, CanvasExt> jiedianui_type_ui = new Dictionary<string, CanvasExt>();
        Dictionary<string, System.Windows.Media.VisualBrush> jiedianui_type_ui_brush = new Dictionary<string, System.Windows.Media.VisualBrush>();
        private System.Windows.Media.VisualBrush GetShapeJiedian(string outType)
        {
            if (jiedianui_type_ui_brush.ContainsKey(outType)) return jiedianui_type_ui_brush[outType];

            var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "接点" && a.BindDataProperty == outType);
            //如果没有指定类型的，则使用默认模型的
            if (typeitem == null) typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "接点");
            if (typeitem == null) return null;


            if (typeitem.EleList == null) return null;

            var EleList = typeitem.EleList;
            var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
            var x2 = (int)EleList.Max(a => Math.Min(a.LocX, a.LocX2) + a.SizeWidth);
            var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
            var y2 = (int)EleList.Max(a => Math.Min(a.LocY, a.LocY2) + a.SizeHeight);
            var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);

            //仅仅操作副本
            var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();

            #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
            foreach (var ele in elelist)
            {
                ele.LocX -= rtshape.X;
                ele.LocY -= rtshape.Y;
                ele.LocX2 -= rtshape.X;
                ele.LocY2 -= rtshape.Y;
                ele.Control_1_X -= rtshape.X;
                ele.Control_1_Y -= rtshape.Y;

                var scaleX = DrawShow.split_arr_col.Average() * 0.7 / (double)rtshape.Width;
                var scaleY = scaleX;

                //var scl1 = 500 / (double)rtshape.Width;
                //按照最大显示高度等比例显示
                var scl2 = typeitem.ShowHeight / (double)rtshape.Height;
                scaleX = scl2;
                scaleY = scaleX;


                ele.LocX *= scaleX;
                ele.LocX2 *= scaleX;
                ele.LocY *= scaleY;
                ele.LocY2 *= scaleY;
                ele.Control_1_X *= scaleY;
                ele.Control_1_Y *= scaleY;
            }
            #endregion

            //图形的容器控件 
            var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
            var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
            var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
            var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));
            var rtContainer = new System.Windows.Rect((double)0, (double)0, xMax - xMin + 1, yMax - yMin + 1);
            //+边缘距离
            rtContainer.X += DrawShow.drawEdge_hor;
            rtContainer.Y += DrawShow.drawEdge_ver;
            //创建容器,基于父容器，父容器为区域容器 
            //var canvasParent = new CanvasExt();
            //canvasParent.Width = rtContainer.Width;
            //canvasParent.Height = rtContainer.Height;
            //DrawShow.cvDrawMain.Children.Add(canvasParent);
            //rtContainer.Offset(-System.Windows.Controls.Canvas.GetLeft(canvasParent), -System.Windows.Controls.Canvas.GetTop(canvasParent));
            var cvNew = DrawShow.doAddDrawEleContainer_Jiedian(rtContainer);
            //子元素放入到父容器中
            foreach (var ele in elelist)
            {
                DrawShow.doAddDrawEleControl(ele, cvNew);
            }
            var bs = new System.Windows.Media.VisualBrush(cvNew);
            jiedianui_type_ui_brush.Add(outType, bs);
            jiedianui_type_ui.Add(outType, cvNew);
            return bs;
        }

        private void loadChildInAreaFromCache(System.Windows.Controls.Canvas canvasParent, HKP_ToolSysReqDto currentSysObj, long blockId)
        {
            var sys_name = currentSysObj?.SysNo;
            var sys_type = currentSysObj?.OutType;

            ItemsDto<HKP_TakeoffDto> res = lst_takeoff;
            var paidian_dist = numFitDistence.Value * 1000;

            if (res != null && res.result != null)
            {
                jiedian_lst_curr = res.result.items;
                jiedian_lst_curr = jiedian_lst_curr.Where(a => a.BlockId == blockId).ToArray();

                //未指定系统时，不显示接点
                if (!string.IsNullOrEmpty(sys_name))
                {
                    jiedian_lst_curr = jiedian_lst_curr.Where(o => o.SysName == sys_name).ToArray();
                }
                else jiedian_lst_curr = new HKP_TakeoffDto[0];

                

                

                //var xcenter = DrawShow.split_arr_col.Average() / 2;
                //var ycenter = DrawShow.split_arr_row.Average() / 2;
                //xcenter += DrawShow.drawEdge_hor;
                //ycenter += DrawShow.drawEdge_ver;

                //当前机台id
                HKP_ToolDto currtool = null;
                if (cbJT.SelectedItem != null) currtool = cbJT.SelectedItem as HKP_ToolDto;


                ItemsDto<HKP_HDCDto> listhdcsysno = new ItemsDto<HKP_HDCDto>();
                if (!string.IsNullOrEmpty(sys_name))
                {
                    string url = string.Format(apiHDC + "GetList?skipCount={0}&maxResultCount={1}&&keyWords={2}&building={3}&floor={4}&fabArea={5}&sysNo={6}", 0, 9999, "", "", "", "", sys_name.ToString());
                    var result = client.Get(url);
                    listhdcsysno = JsonConvert.DeserializeObject<ItemsDto<HKP_HDCDto>>(result);
                }


                foreach (HKP_TakeoffDto item in jiedian_lst_curr)
                {
                    //if (item.TakeoffName == "D-Au-L20-E9-4")
                    //{

                    //}
                    var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "接点" && a.BindDataProperty == item.OutType);
                    if (typeitem == null) typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "接点");

                    //所有接点显示大小相同，因此使用同一个模板  
                    var cv_template_brush = GetShapeJiedian(item.OutType);
                    if (cv_template_brush == null) continue;
                    var cv_template = jiedianui_type_ui[item.OutType];


                    var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, cv_template.Width, cv_template.Height);
                    //+边缘距离
                    rtContainer.X += DrawShow.drawEdge_hor;
                    rtContainer.Y += DrawShow.drawEdge_ver;
                    //创建容器,基于父容器，父容器为区域容器.此处不使用相对于区域的坐标。直接加入到初始父级，防止元素超出区域范围不能正常显示。
                    //rtContainer.Offset(-System.Windows.Controls.Canvas.GetLeft(canvasParent), -System.Windows.Controls.Canvas.GetTop(canvasParent));
                    var cvNew = DrawShow.doAddDrawEleContainer_Jiedian(canvasParent, rtContainer);
                    //防止元素超出区域范围不能正常显示。
                    System.Windows.Controls.Panel.SetZIndex(cvNew, int.MaxValue);

                    #region 容器的颜色  已派点的显示为红色；未派点可派点的显示为绿色；  
                    //已派点的显示为红色；未派点可派点的显示为绿色；  
                    //机台位置在画布中心 

                    #region ES
                    //电力系统
                    if (currentSysObj.SysNo == "ES")
                    {
                        bool goon = false;
                        if (listhdcsysno?.result?.items != null)
                        {
                            foreach (var itemhdcno in listhdcsysno.result.items)
                            {
                                if (itemhdcno.ToolSysReqId == currentSysObj.Id && itemhdcno.TakeoffNo == item.TakeoffNo)
                                {
                                    cvNew.Background = brush_paidian_NO;//一个机台的接点不允许重复派点,这个接点派到上选择的机台接点上面，用棕色表示
                                    goon = true;
                                    break;
                                }
                            }
                        }
                        if (!goon) {
                            //如果是I-Line-盘
                            if (item.PointType == "1")
                            {
                                if (item.Used)
                                {
                                    cvNew.Background = brush_paidian_used;//红色
                                }
                                else
                                {
                                    //FlowPeak  容量  FlowUnit 容量单位  PressurePeak 电压  PressureUnit 电源种类   电盘的容量信息存到管道，所以要计算管道的信息

                                    HKP_SubmainDto submin = lst_guandao.result?.items?.FirstOrDefault(a => a.Id == item.SubmainId);

                                    if (currentSysObj.OutSizeUnit == submin.PressureUnit)
                                    {
                                        if (Convert.ToInt32(currentSysObj.OutSize) < 220)
                                        {
                                            if (Convert.ToInt32(submin.PressurePeak) >= 220)
                                            {
                                                cvNew.Background = brush_paidian_used;//机台需求220V以下电压，大于220V的电压不允许派点
                                            }
                                            else
                                            {
                                                if (Convert.ToInt32(submin.PressurePeak) >= Convert.ToInt32(currentSysObj.OutSize))
                                                {
                                                    //decimal takeoffFlow = item.FlowPeak - item.UsedFlow;
                                                    //208V 会占用电盘3个接口
                                                    int usdpoint = 0;
                                                    if (currentSysObj.OutSize == "208")
                                                    {
                                                        usdpoint = 3;
                                                    }
                                                    else
                                                    {
                                                        usdpoint = 1;
                                                    }

                                                    bool point = Convert.ToDouble(submin.Allpoint) - Convert.ToDouble(submin.usedpoint) >= usdpoint;
                                                    double toolRongL = Utils.ToInA(currentSysObj.FlowPeak.ToString(), currentSysObj.FlowUnit);//机台负荷算出安培
                                                    if (toolRongL <= 0)
                                                    {
                                                        toolRongL = Utils.ToInA(currentSysObj.Power.ToString(), currentSysObj.PowerUnit);//功率算出安培
                                                    }
                                                    bool  yellowtype = Convert.ToDouble(submin.FlowPeak) * 0.8 > toolRongL + Convert.ToDouble(submin.numUsedFlow);
                                                    bool greentype = Convert.ToDouble(submin.FlowPeak) > toolRongL + Convert.ToDouble(submin.numUsedFlow);
                                                    if (toolRongL > 0)
                                                    {
                                                        if (point == true && yellowtype == true)
                                                        {
                                                            //如果开槽的容量大于机台需要的容量可以派点
                                                            jiedian_canp.Add(item);
                                                            cvNew.Background = brush_paidian_touse;//绿色
                                                        }
                                                        else if (point == true && yellowtype == false && greentype == true)
                                                        {
                                                            //80%不满足需求了
                                                            jiedian_canp.Add(item);
                                                            cvNew.Background = brush_paidian_yellow;
                                                        }
                                                        else if (point == true && greentype == false)
                                                        {
                                                            if (currentSysObj.isPaiDian)
                                                            {
                                                                //如果这个接点已经派过，可以占用多个接口
                                                                jiedian_canp.Add(item);
                                                                cvNew.Background = brush_paidian_yellow;
                                                            }
                                                            else
                                                            {
                                                                //容量量不够
                                                                cvNew.Background = brush_paidian_used;
                                                            }
                                                            
                                                        }
                                                        else if (point == false)
                                                        {
                                                            //容量量不够
                                                            cvNew.Background = brush_paidian_used;
                                                        }
                                                    }
                                                    else//如果得不到机台所需呀的容量，不允许派点
                                                    {
                                                        cvNew.Background = brush_paidian_used;
                                                    }

                                                }
                                                else
                                                {
                                                    cvNew.Background = brush_paidian_used;
                                                }
                                            }
                                        }
                                        if (Convert.ToInt32(currentSysObj.OutSize) >= 220)
                                        {
                                            if (Convert.ToInt32(submin.PressurePeak) < 220)
                                            {
                                                cvNew.Background = brush_paidian_used;//机台需求220V以下电压，大于220V的电压不允许派点
                                            }
                                            else
                                            {
                                                if (Convert.ToInt32(submin.PressurePeak) >= Convert.ToInt32(currentSysObj.OutSize))
                                                {
                                                    //380V 也会占用电盘3个接口
                                                    int usdpoint = 1;
                                                    if (currentSysObj.OutSize == "380")
                                                    {
                                                        usdpoint = 3;
                                                    }
                                                    else
                                                    {
                                                        usdpoint = 1;
                                                    }
                                                    //decimal takeoffFlow = item.FlowPeak - item.UsedFlow;
                                                    bool point = Convert.ToDouble(submin.Allpoint) - Convert.ToDouble(item.Point) >= usdpoint;
                                                    double toolRongL = Utils.ToInA(currentSysObj.FlowPeak.ToString(), currentSysObj.FlowUnit);//机台负荷算出安培
                                                    if (toolRongL <= 0)
                                                    {
                                                        toolRongL = Utils.ToInA(currentSysObj.Power.ToString(), currentSysObj.PowerUnit);//功率算出安培
                                                    }
                                                    bool yellowtype = Convert.ToDouble(submin.FlowPeak) * 0.8 > toolRongL + Convert.ToDouble(submin.numUsedFlow);
                                                    bool  greentype = Convert.ToDouble(submin.FlowPeak) > toolRongL + Convert.ToDouble(submin.numUsedFlow);
                                                    if (toolRongL > 0)
                                                    {
                                                        
                                                        
                                                        if (point==true && yellowtype == true)
                                                        {
                                                            //如果开槽的容量大于机台需要的容量可以派点
                                                            jiedian_canp.Add(item);
                                                            cvNew.Background = brush_paidian_touse;//绿色
                                                        }
                                                        else if (point==true && yellowtype==false && greentype==true)
                                                        {
                                                            //80%不满足需求了
                                                            jiedian_canp.Add(item);
                                                            cvNew.Background = brush_paidian_yellow;
                                                        }
                                                        else if (point==true && greentype==false)
                                                        {
                                                            if (currentSysObj.isPaiDian)
                                                            {
                                                                //如果这个接点已经派过，可以占用多个接口
                                                                jiedian_canp.Add(item);
                                                                cvNew.Background = brush_paidian_yellow;
                                                            }
                                                            else
                                                            {
                                                                //容量量不够
                                                                cvNew.Background = brush_paidian_used;
                                                            }
                                                           
                                                        }
                                                        else if(point==false)
                                                        {
                                                            //容量量不够
                                                            cvNew.Background = brush_paidian_used;
                                                        }

                                                    }
                                                    else//如果得不到机台所需呀的容量，不允许派点
                                                    {
                                                        cvNew.Background = brush_paidian_used;
                                                    }

                                                }
                                                else
                                                {
                                                    cvNew.Background = brush_paidian_used;
                                                }
                                            }
                                        }
                                    }
                                    //电源种类不同，不允许派点
                                    else
                                    {
                                        cvNew.Background = brush_paidian_used;//红色
                                    }

                                }
                            }
                            else
                            {
                                //母线插槽已经用掉了插槽不可继续派
                                if (item.Used)
                                {
                                    cvNew.Background = brush_paidian_used;//红色
                                }
                                else
                                {
                                    //业主所述：N点只能接N电，U电只能接U电
                                    if (currentSysObj.OutSizeUnit == item.OutSizeUnit)
                                    {
                                       if(Convert.ToInt32(currentSysObj.OutSize) < 220)
                                        {
                                            if (Convert.ToInt32(item.OutSize) >= 220)
                                            {
                                                cvNew.Background = brush_paidian_used;//红色
                                            }
                                            else
                                            {
                                                //判断电压
                                                if (Convert.ToInt32(item.OutSize) >= Convert.ToInt32(currentSysObj.OutSize))
                                                {
                                                    double toolRongL = Utils.ToInA(currentSysObj.FlowPeak.ToString(), currentSysObj.FlowUnit);//机台负荷算出安培
                                                    if (toolRongL <= 0)
                                                    {
                                                        toolRongL = Utils.ToInA(currentSysObj.Power.ToString(), currentSysObj.PowerUnit);//功率算出安培
                                                    }
                                                    if (toolRongL > 0)
                                                    {
                                                        if (Convert.ToDouble(item.FlowPeak) > toolRongL)
                                                        {
                                                            //如果开槽的容量大于机台需要的容量可以派点
                                                            jiedian_canp.Add(item);
                                                            cvNew.Background = brush_paidian_touse;
                                                        }
                                                        else
                                                        {
                                                            //容量量不够
                                                            cvNew.Background = brush_paidian_used;


                                                        }
                                                    }
                                                    else//如果得不到机台所需呀的容量，不允许派点
                                                    {
                                                        cvNew.Background = brush_paidian_used;

                                                    }
                                                }
                                                else
                                                {
                                                    cvNew.Background = brush_paidian_used;//电压小于需求电压，不允许派点
                                                }

                                            }
                                        }

                                       if(Convert.ToInt32(currentSysObj.OutSize) >= 220)
                                        {
                                            if (Convert.ToInt32(item.OutSize) < 220)
                                            {
                                                cvNew.Background = brush_paidian_used;//红色
                                            }
                                            else
                                            {
                                                //判断电压
                                                if (Convert.ToInt32(item.OutSize) >= Convert.ToInt32(currentSysObj.OutSize))
                                                {
                                                    double toolRongL = Utils.ToInA(currentSysObj.FlowPeak.ToString(), currentSysObj.FlowUnit);//机台负荷算出安培
                                                    if (toolRongL <= 0)
                                                    {
                                                        toolRongL = Utils.ToInA(currentSysObj.Power.ToString(), currentSysObj.PowerUnit);//功率算出安培
                                                    }
                                                    if (toolRongL > 0)
                                                    {


                                                        if (Convert.ToDouble(item.FlowPeak) > toolRongL)
                                                        {
                                                            //如果开槽的容量大于机台需要的容量可以派点
                                                            jiedian_canp.Add(item);
                                                            cvNew.Background = brush_paidian_touse;
                                                        }
                                                        else
                                                        {
                                                            //容量量不够
                                                            cvNew.Background = brush_paidian_used;


                                                        }
                                                    }
                                                    else//如果得不到机台所需呀的容量，不允许派点
                                                    {
                                                        cvNew.Background = brush_paidian_used;

                                                    }
                                                }
                                                else
                                                {
                                                    cvNew.Background = brush_paidian_used;//电压小于需求电压，不允许派点
                                                }
                                            }

                                        }

                                    }
                                    else
                                    {
                                        cvNew.Background = brush_paidian_used;//电源种类不同，不允许派点
                                    }

                                    //double toolRol=Utils.ToInA()
                                }

                            }

                        }
                    }
                    #endregion
                    else
                    {
                        //未派点的，可派点
                        var canConnected = lst_jt_sys?.result?.items?.Any(b =>
                         //b.OutType == item.OutType
                         b.ToolId.ToString() == currtool?.Id
                         && !item.Used
                         && item.Enabled
                         //&& Utils.ToInMM(item.OutSize, item.OutSizeUnit) >= Utils.ToInMM(b.OutSize, b.OutSizeUnit) //接点尺寸
                         && jt_rect.IsVisible((int)((int)item.X + DrawShow.drawEdge_hor), (int)((int)item.Y + DrawShow.drawEdge_ver)) //距离
                        );

                        //已派点
                        var connected = lst_jt_sys?.result?.items?.Any(b =>
                         //b.OutType == item.OutType
                         b.ToolId.ToString() == currtool?.Id
                        && item.Used
                        //&& Utils.ToInMM(item.OutSize, item.OutSizeUnit) >= Utils.ToInMM(b.OutSize, b.OutSizeUnit) //流量
                        && jt_rect.IsVisible((int)((int)item.X + DrawShow.drawEdge_hor), (int)((int)item.Y + DrawShow.drawEdge_ver))//距离
                        );
                        if (connected == true)
                        {

                            #region 其他系统派点
                            bool goon = false;
                            if (listhdcsysno?.result?.items != null)
                            {
                                foreach (var itemhdcno in listhdcsysno.result.items)
                                {
                                    if (itemhdcno.AprvStatus == "A" && itemhdcno.TakeoffNo == item.TakeoffNo)
                                    {
                                        cvNew.Background = brush_paidian_used;//这个takeoff点的HDC已经审核了，已经审核的takeoff电不允许在派点，除非删除HDC
                                        goon = true;
                                        break;
                                    }
                                    if (itemhdcno.ToolSysReqId == currentSysObj.Id && itemhdcno.TakeoffNo == item.TakeoffNo)
                                    {
                                        cvNew.Background = brush_paidian_NO;//一个机台的接点不允许重复派点,这个接点派到上选择的机台接点上面，用棕色表示
                                        goon = true;
                                        break;
                                    }
                                }
                            }

                            if (!goon)
                            {
                                double takeoffsize = Utils.ToInMM(item.OutSize, item.OutSizeUnit);
                                //算出takeoff点的横截面积
                                double takeR = takeoffsize / 2;
                                takeoffsize = takeR * takeR * 3.14;
                                //这是机台已经使用了的截面积
                                double usedsize = Convert.ToDouble(item.UsedFlow);
                                //接点的尺寸大小
                                double xysize = Utils.ToInMM(currentSysObj.OutSize, currentSysObj.OutSizeUnit);
                                double jdR = xysize / 2;
                                xysize = jdR * jdR * 3.14;
                                //bool yellow = takeoffsize * 0.8 < usedsize+xysize;//true则说明takeoff点的使用已经超过了80%



                                bool isPaiDokyellow = takeoffsize - usedsize > xysize;//true表示全部剩余口径依然满足机台接口需求
                                bool isPaiDokblue = takeoffsize * 0.8 - usedsize > xysize;//true表示takeoff点80%的剩余口径依然满足机台接口需求

                                if (!isPaiDokblue && isPaiDokyellow)
                                {
                                    jiedian_canp.Add(item);
                                    cvNew.Background = brush_paidian_yellow;//已经派过的takeoff点使用率已经超过80%,并且还满足派点的要求，用黄色
                                                                            //cvNew.Background = brush_paidian_touse;
                                }
                                if (isPaiDokblue && isPaiDokyellow)
                                {
                                    jiedian_canp.Add(item);
                                    cvNew.Background = brush_paidian_blue;//已经派过的takeoff点使用率已经超过80%,并且还满足派点的要求，用黄色
                                }
                                if (!isPaiDokyellow)
                                {
                                    cvNew.Background = brush_paidian_used;//已经派过的takeoff点，已经不满足takeoff点的要求了，用红色，不能派点
                                }
                            }
                            #endregion

                        }
                        else if (canConnected == true)
                        {
                            jiedian_canp.Add(item);
                            cvNew.Background = brush_paidian_touse;
                        }
                        else if(canConnected==false)
                        {
                            //接点尺寸不满足，用红色
                            cvNew.Background = brush_paidian_used;
                        }
                        
                    }
                    #endregion
                    

                    //使用模板作为背景展示图形  
                    var cvbg = DrawShow.doAddBgCanvas(cvNew);
                    cvbg.Background = cv_template_brush;


                    //列表转化
                    item.BlockName = lst_block.result?.items?.FirstOrDefault(a => a.Id == item.BlockId)?.BlockName;
                    item.SubmainName = lst_guandao.result?.items?.FirstOrDefault(a => a.Id == item.SubmainId)?.SubmainName;
                    cvNew.ToolTip = new UC_Tooltip_Jiedian(item);
                    System.Windows.Controls.ToolTipService.SetShowDuration(cvNew, 10000);
                    cvNew.Data_Jiedian = item;
                    //区域的快捷菜单
                    container_Jiedian_Menu(cvNew, item);
                    //添加文本说明
                    DrawShow.doAddDrawEleContainer_Desc_Jiedian(cvNew, item.TakeoffNo, typeitem.ShowHeight);

                }
            }
        }

        private string GetJiedianTooltip(HKP_TakeoffDto dto, HKP_ToolDto tool, double Distence = 0d)
        {
            StringBuilder tips = new StringBuilder();
            tips.AppendLine("接点编号：" + dto.TakeoffNo);
            tips.AppendLine("所属系统：" + dto.SysName);
            tips.AppendLine("接点尺寸：" + dto.OutSize + dto.OutSizeUnit);
            tips.AppendLine("接点流量：" + dto.FlowPeak + dto.FlowUnit);
            tips.AppendLine("接点类型：" + dto.OutType);
            tips.AppendLine("已使用：" + dto.Used);
            tips.AppendLine("接点启用：" + dto.Enabled);
            tips.AppendLine("接点坐标：X=" + dto.X.ToString() + "，Y=" + dto.Y.ToString());
            tips.AppendLine("机台名称：" + (tool == null ? "" : (tool.ToolModel + tool.ToolName)));
            tips.AppendLine("机台坐标：X=" + (tool == null ? "" : (tool.X.ToString() + "，Y=" + tool.Y.ToString())));
            tips.AppendLine("距离：" + Distence.ToString() + "m");

            return tips.ToString();
        }

        /// <summary>
        /// 机台查询
        /// </summary>
        /// <param name="keyWords"></param>
        /// <param name="maxResultCount"></param>
        private void LoadHKPTool(string keyWords, int maxResultCount = 999999, int skipCount = 0)
        {
            string url = string.Format("api/services/app/HKP_Tool/GetList?maxResultCount={0}&keyWords={1}&skipCount={2}", maxResultCount, keyWords, skipCount);
            var result = client.Get(url);
            ItemsDto<HKP_ToolDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolDto>>(result);
            //dataGridViewS.DataSource = res?.result?.items;
            FromSetting[] fromSettings = new FromSetting[16];
            fromSettings[0] = new FromSetting { FieldDisplay = "机台编号" };
            fromSettings[1] = new FromSetting { FieldDisplay = "机台名称" };
            fromSettings[2] = new FromSetting { FieldDisplay = "机台型号" };
            fromSettings[4] = new FromSetting { FieldDisplay = "供应商" };
            fromSettings[5] = new FromSetting { FieldDisplay = "系统需求" };
            fromSettings[6] = new FromSetting { FieldDisplay = "长度" };
            fromSettings[7] = new FromSetting { FieldDisplay = "宽度" };
            fromSettings[8] = new FromSetting { FieldDisplay = "高度" };
            fromSettings[9] = new FromSetting { FieldDisplay = "重量" };
            fromSettings[10] = new FromSetting { FieldDisplay = "状态" };
            fromSettings[11] = new FromSetting { FieldDisplay = "版本" };
            fromSettings[12] = new FromSetting { FieldDisplay = "分类ID" };
            fromSettings[13] = new FromSetting { FieldDisplay = "震动源" };
            fromSettings[14] = new FromSetting { FieldDisplay = "基座需求" };
            fromSettings[15] = new FromSetting { FieldDisplay = "盛水需求" };
            //Utils.SetHeader(dataGridViewS, fromSettings);

            //dgvTool.DataSource = res?.result?.items;
            //FromSetting[] settings = new FromSetting[2];
            //settings[0] = new FromSetting { FieldDisplay = "机台编号" };
            //settings[1] = new FromSetting { FieldDisplay = "机台名称" };
            //Utils.SetHeader(dgvTool, settings);
        }


        private void ReDraw()
        {
            try
            {
                GetFoorDrawingCache();
                BindUI_Draw();
                //DrawShow.ShowMapAll();
            }
            catch (Exception ex)
            {
            }
        }

        private void Refresh_Quyu()
        {
            //区域
            var url = string.Format("api/services/app/HKP_Block/GetList?maxResultCount=9999&building={0}&floor={1}", "", "");
            var result = client.Get(url);
            lst_block = JsonConvert.DeserializeObject<ItemsDto<HKP_BlockDto>>(result);
        }

        /// <summary>
        /// 接点
        /// </summary>
        private void Refresh_Jiedian()
        {
            var url = string.Format("api/services/app/HKP_Takeoff/GetList?maxResultCount=99999&blockId={0}", 0);
            var result = client.Get(url);
            lst_takeoff = JsonConvert.DeserializeObject<ItemsDto<HKP_TakeoffDto>>(result);
        }

        /// <summary>
        /// 管道
        /// </summary>
        private void Refresh_Guandao()
        {
            var url = "api/services/app/HKP_Submain/";
            string act = string.Format(url + "GetList?maxResultCount=9999");
            var result = client.Get(act);
            lst_guandao = JsonConvert.DeserializeObject<ItemsDto<HKP_SubmainDto>>(result);
        }
        private System.Windows.Controls.UserControl ucInst = null;
        private void RefreshData(bool delayLoadJiedain = false)
        {
            //获取自定义图形 
            MyCustomerList = LocalDataHelper.GetShapeList(ucInst, "");

            //建筑  
            Refresh_Building();

            //系统
            Refresh_Sys();

            //区域
            Refresh_Quyu();

            //接点  首次加载时，由于没有选择系统，可以延迟加载，提速
            if (!delayLoadJiedain)
            {
                Refresh_Jiedian();
            }
            else
            {
                Task.Run(delegate
                {
                    Thread.Sleep(1000);
                    Refresh_Jiedian();
                });
            }

            //管道
            Refresh_Guandao();

            //机台
            Refresh_Jitai();

            //机台下的接口
            Refresh_Jtsys();
        }


        private void Refresh_Jtsys()
        {
            string url = string.Format(apiSysReq + "GetList?toolId={0}&skipCount=0&maxResultCount=99999", "");
            var result = client.Get(url);
            lst_jt_sys = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolSysReqDto>>(result);
        }

        private void Refresh_Building()
        {
            string url = string.Format("api/services/app/HKP_Category/GetList?layout={0}&parentId={1}", "Building", -1);
            client = new APIClient(webAPI);
            var result = client.Get(url);
            lst_buildfloor = JsonConvert.DeserializeObject<ItemsDto<HKP_CategoryDto>>(result);

        }

        private void Refresh_Sys()
        {
            var url = string.Format("api/services/app/HKP_System/GetList?maxResultCount={0}", 99999);
            var result = client.Get(url);
            lst_system = JsonConvert.DeserializeObject<ItemsDto<HKP_SystemDto>>(result);

        }

        private void Refresh_Jitai()
        {
            var url = string.Format("api/services/app/HKP_Tool/GetList?maxResultCount={0}&keyWords={1}&skipCount={2}", int.MaxValue, "", 0);
            var result = client.Get(url);
            lst_tool = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolDto>>(result);


            ////机台对应接口数据
            //toolSysReqDict.Clear();
            //if ((lst_tool?.result?.items).Any())
            //{
            //    foreach (var t in lst_tool.result.items)
            //    {
            //        url = string.Format(apiSysReq + "GetList?toolId={0}", t.ToolId);
            //        result = client.Get(url);
            //        ItemsDto<HKP_ToolSysReqDto> dto = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolSysReqDto>>(result);
            //        var rstlst = dto.result.items;
            //        toolSysReqDict.Add(t.ToolId, rstlst);
            //    }
            //}
        }

        private void bindCacheDataToUI()
        {
            BindUI_ListRight();
            GetFoorDrawingCache();
            BindUI_Draw();
        }

        private void BindUI_ListRight()
        {
            //建筑
            building.DataSource = lst_buildfloor.result.items.Where(a => a.ParentId <= 0).ToList();
            building.DisplayMember = "CateName";
            building.ValueMember = "Id";

            //楼层
            if (building.Items.Count > 0)
            {
                building.SelectedIndex = 0;
                var sltid = (building.Items[0] as HKP_CategoryDto).Id;
                floor.DataSource = lst_buildfloor.result.items.Where(a => a.ParentId == sltid).ToList();
                floor.DisplayMember = "CateName";
                floor.ValueMember = "Id";
            }

            //机台  
            FilterJitaiByFloorAndEquip();

            //系统 
            comboBoxSys.DisplayMember = "Name";
            comboBoxSys.ValueMember = "Id";
            comboBoxSys.SelectedIndex = -1;

        }
        private void numFitDistence_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (jt_round_ell != null)
                    DrawShow.cvDrawMain.Children.Remove(jt_round_ell);

                //BindUI_Draw_JTRound();
                BindUI_Draw();
            }
            catch (Exception ex)
            {
            }
        }

        private void FilterJitaiEquipByFloor()
        {
            var sltFloor = (floor.SelectedItem as HKP_CategoryDto)?.CateName?.ToString();

            var lst_tool_floor = lst_tool?.result?.items.Where(a => a.Floor == sltFloor).ToArray();

            //机台按照设备分组的集合
            cbEquipe.Items.Clear();
            cbEquipe.Text = "";
            if ((lst_tool?.result?.items).Any())
            {
                var eqlist = lst_tool_floor.Select(a => a.EquipmentID).Distinct().ToArray();
                cbEquipe.Items.AddRange(eqlist);
            }
        }


        private void FilterJitaiByFloorAndEquip()
        {
            var sltFloor = (floor.SelectedItem as HKP_CategoryDto)?.CateName?.ToString();
            var slt_equpid = cbEquipe.SelectedItem?.ToString();

            var lst_tool_floor = lst_tool?.result?.items.Where(a => a.Floor == sltFloor).ToArray();

            //机台按照
            if (SysLst_tool != null)
            {
                lst_tool_floor = SysLst_tool?.result?.items.Where(a => a.Floor == sltFloor).ToArray();
                cbJT.DataSource = lst_tool_floor.Where(a => a.EquipmentID == slt_equpid).ToList();
                cbJT.DisplayMember = "ToolName";
                cbJT.ValueMember = "ToolId";
                cbJT.SelectedIndex = -1;
            }
            else
            {
                cbJT.DataSource = lst_tool_floor.Where(a => a.EquipmentID == slt_equpid).ToList();
                cbJT.DisplayMember = "ToolName";
                cbJT.ValueMember = "ToolId";
                cbJT.SelectedIndex = -1;
            }

           
        }

        System.Windows.Shapes.Ellipse jt_round_ell = null;
        System.Drawing.Region jt_rect = null;
        private void BindUI_Draw_JTRound()
        {
            var tool = cbJT.SelectedItem as HKP_ToolDto;
            if (tool == null) return;

            //机台半径附近 
            var x = (int)(DrawShow.split_arr_col.Sum() / 2);
            var y = (int)(DrawShow.split_arr_row.Sum() / 2);
            x = (int)tool.X;
            y = (int)tool.Y;

            var rt = new System.Windows.Rect(x, y, 1, 1);
            var lenhalf = (double)numFitDistence.Value * 1000;
            rt.Inflate(lenhalf, lenhalf);
            rt.Offset(DrawShow.drawEdge_hor, DrawShow.drawEdge_ver);

            var gp = new GraphicsPath();
            gp.AddEllipse((int)rt.X, (int)rt.Y, (int)rt.Width, (int)rt.Height);
            jt_rect = new Region(gp);

            jt_round_ell = DrawShow.doAddDrawEle_JTRound(rt);
        }

        List<HKP_TakeoffDto> jiedian_canp = new List<HKP_TakeoffDto>();
        private void BindUI_Draw()
        {
            DrawShow.ClearDrawList();
            jiedianui_type_ui.Clear();
            jiedianui_type_ui_brush.Clear();
            jiedian_canp.Clear();
            //清除接点的信息
            jiedian_lst_curr = null;

            var name_block = building.Text;
            var name_floor = floor.Text;


            //机台半径附近 
            BindUI_Draw_JTRound();



            #region 区域 + 接点
            ItemsDto<HKP_BlockDto> res = lst_block;
            if (res != null && res.result != null)
            {
                var sysitem = comboBoxSys.SelectedItem as HKP_ToolSysReqDto;
                var blocks_curr = res.result.items;
                blocks_curr = blocks_curr.Where(a => a.Building == name_block && a.Floor == name_floor).ToArray();
                foreach (HKP_BlockDto item in blocks_curr)
                {
                    var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "区域");
                    if (typeitem == null) continue;

                    if (typeitem.EleList != null)
                    {
                        var EleList = typeitem.EleList;

                        var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
                        var x2 = (int)EleList.Max(a => Math.Max(a.LocX, a.LocX2));
                        var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
                        var y2 = (int)EleList.Max(a => Math.Max(a.LocY, a.LocY2));

                        var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                        if (rtshape.Width <= 0 || rtshape.Height <= 0) continue;

                        //仅仅操作副本
                        var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();

                        #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
                        foreach (var ele in elelist)
                        {
                            ele.LocX -= rtshape.X;
                            ele.LocY -= rtshape.Y;
                            ele.LocX2 -= rtshape.X;
                            ele.LocY2 -= rtshape.Y;
                            ele.Control_1_X -= rtshape.X;
                            ele.Control_1_Y -= rtshape.Y;

                            var scaleX = (double)item.Width / (double)rtshape.Width;
                            var scaleY = (double)item.Length / (double)rtshape.Height;

                            ele.LocX *= scaleX;
                            ele.LocX2 *= scaleX;
                            ele.LocY *= scaleY;
                            ele.LocY2 *= scaleY;
                            ele.Control_1_X *= scaleX;
                            ele.Control_1_Y *= scaleY;
                        }
                        #endregion

                        //图形的容器控件 
                        var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
                        var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
                        var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
                        var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));
                        var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, xMax - xMin + 1, yMax - yMin + 1);
                        //+边缘距离
                        rtContainer.X += DrawShow.drawEdge_hor;
                        rtContainer.Y += DrawShow.drawEdge_ver;
                        //创建容器
                        var cvNew = DrawShow.doAddDrawEleContainer_Quyu(rtContainer);
                        //区域的快捷菜单
                        container_Quyu_Menu(cvNew, item);
                        //子元素放入到父容器中
                        foreach (var ele in elelist)
                        {
                            DrawShow.doAddDrawEleControl(ele, cvNew);
                        }
                        //添加文本说明
                        DrawShow.doAddDrawEleContainer_Desc_Quyu(cvNew, item.BlockName);

                        //加载区域内节点 
                        loadChildInAreaFromCache(DrawShow.cvDrawMain, sysitem, item.Id);

                    }
                    //元素事件处理
                }
            }

            #endregion

            #region 管道 
            ItemsDto<HKP_SubmainDto> res_gd = lst_guandao;
            var currentSys = comboBoxSys.Text;
            if (res_gd != null && res_gd.result != null)
            {
                //当前所选的系统编号
                var sysReqArr = lst_jt_sys.result?.items?.ToArray();
                var sltsysid = comboBoxSys.SelectedValue?.ToString();
                currentSys = sysReqArr.FirstOrDefault(a => a.Id.ToString() == sltsysid)?.SysNo;

                var guandaos_curr = res_gd.result.items;
                //过滤系统 不指定系统时，不加载管道
                if (!string.IsNullOrEmpty(currentSys))
                {
                    guandaos_curr = guandaos_curr.Where(o => o.SysNo == currentSys).ToArray();
                }
                else guandaos_curr = new HKP_SubmainDto[0];
                //过滤楼层、建筑 
                var floor_slt = (floor.SelectedItem as HKP_CategoryDto)?.CateName?.ToString();
                var building_slt = (building.SelectedItem as HKP_CategoryDto).CateName;
                guandaos_curr = guandaos_curr?.Where(a => a.Floor == floor_slt && a.Building == building_slt).ToArray();


                foreach (HKP_SubmainDto item in guandaos_curr)
                {
                    var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "管道" && a.BindDataProperty == item.SysNo);
                    //if (typeitem == null) typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "管道");
                    if (typeitem == null) continue;

                    if (typeitem.EleList != null)
                    {
                        var EleList = typeitem.EleList;
                        //var x1 = (int)EleList.Min(a => a.LocX);
                        //var x2 = (int)EleList.Max(a => a.LocX + a.SizeWidth);
                        //var y1 = (int)EleList.Min(a => a.LocY);
                        //var y2 = (int)EleList.Max(a => a.LocY + a.SizeHeight);

                        var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
                        var x2 = (int)EleList.Max(a => Math.Max(a.LocX, a.LocX2));
                        var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
                        var y2 = (int)EleList.Max(a => Math.Max(a.LocY, a.LocY2));

                        var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                        if (rtshape.Width <= 0 || rtshape.Height <= 0) continue;

                        //仅仅操作副本
                        var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();


                        #region 管道颜色控制
                        //管道图形绑定了管道业务数据，能够实时展现管道流量状况（正常流量显示蓝色、超过阈值显示红色）。
                        //计算方式：
                        //此管道业务数据里面的操作流量和此管道所有接点业务数据的操作流量之和做对比，大于则此管道显示红色，正常则显示蓝色
                        var parentFlow = item.FlowPeakOperation;

                        bool usedyellow = item.usedpoint >= item.Allpoint*0.8;//超过80%的接点已使用 管道画黄色
                        bool usedred =  item.usedpoint >= item.Allpoint*0.95;//超过95的接点使用

                        bool yellowFlow = Convert.ToDouble(item.numUsedFlow) > Convert.ToInt32(item.FlowPeak) * 0.8;
                        bool redFlow = Convert.ToDecimal(item.numUsedFlow) > item.FlowPeak;

                        //该管道关联的所有接点的操作流量之和
                        // var childlist = lst_takeoff.result.items.Where(a => a.SubmainName == item.SubmainName).ToList();
                        // decimal childFlowSum = 0;
                        // if (childlist.Any()) 
                        //     childFlowSum = childlist.Sum(a => a.FlowPeakOperation);
                        //System.Windows.Media.SolidColorBrush bsRst = System.Windows.Media.Brushes.Blue;
                        //if (parentFlow > childFlowSum) 
                        //    bsRst = System.Windows.Media.Brushes.Red;
                        System.Windows.Media.SolidColorBrush bsRst = System.Windows.Media.Brushes.Blue;
                        if (usedyellow && !usedred)
                        {
                            bsRst = System.Windows.Media.Brushes.Yellow;
                        }       
                        if (usedred)
                        {
                            bsRst = System.Windows.Media.Brushes.Red;
                        }
                        if (yellowFlow == true)
                        {
                            bsRst = System.Windows.Media.Brushes.Yellow;
                        }
                        if (redFlow == true)
                        {
                            bsRst = System.Windows.Media.Brushes.Red;
                        }

                        foreach (var ele in elelist)
                        {
                            ele.Stroke = bsRst;
                            ele.Fill = bsRst;
                        }
                        #endregion



                        #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
                        foreach (var ele in elelist)
                        {
                            ele.LocX -= rtshape.X;
                            ele.LocY -= rtshape.Y;
                            ele.LocX2 -= rtshape.X;
                            ele.LocY2 -= rtshape.Y;
                            ele.Control_1_X -= rtshape.X;
                            ele.Control_1_Y -= rtshape.Y;

                            var scaleX = (double)item.Width / (double)rtshape.Width;
                            var scaleY = (double)item.Length / (double)rtshape.Height;

                            ele.LocX *= scaleX;
                            ele.LocX2 *= scaleX;
                            ele.LocY *= scaleY;
                            ele.LocY2 *= scaleY;
                            ele.Control_1_X *= scaleX;
                            ele.Control_1_Y *= scaleY;
                        }
                        #endregion

                        //图形的容器控件
                        //var xMin = elelist.Min(a => a.LocX);
                        //var xMax = elelist.Max(a => a.LocX2);
                        //var yMin = elelist.Min(a => a.LocY);
                        //var yMax = elelist.Max(a => a.LocY2);

                        var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
                        var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
                        var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
                        var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));
                        //if (xMax - xMin + 1 <= 0 || yMax - yMin + 1 <= 0)
                        //{ 
                        //} 
                        var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, xMax - xMin + 1, yMax - yMin + 1);

                        //+边缘距离
                        rtContainer.X += DrawShow.drawEdge_hor;
                        rtContainer.Y += DrawShow.drawEdge_ver;
                        //创建容器
                        var cvNew = DrawShow.doAddDrawEleContainer_Guandao(rtContainer);
                        //列表转化
                        item.SubmainName = lst_guandao.result?.items?.FirstOrDefault(a => a.SubmainNo == item.SubmainNo)?.SubmainName;
                        cvNew.ToolTip = new UC_Tooltip_Guandao(item);
                        System.Windows.Controls.ToolTipService.SetShowDuration(cvNew, 10000);
                        //区域的快捷菜单
                        //container_Quyu_Menu(cvNew, item);
                        //子元素放入到父容器中
                        foreach (var ele in elelist)
                        {
                            DrawShow.doAddDrawEleControl(ele, cvNew);
                        }
                        //添加文本说明
                        //DrawShow.doAddDrawEleContainer_Desc_Quyu(cvNew, item.SubmainName);

                        ////加载区域内节点
                        //loadChildInArea(cvNew, comboBoxSys.SelectedValue?.ToString(), item.Id);

                    }
                }
            }
            #endregion

            #region 机台 
            ItemsDto<HKP_ToolDto> res_jt = lst_tool;
            if (res_jt != null && res_jt.result != null
                //&& cbJT.SelectedItem != null
                )
            {
                var guanjds_curr = res_jt.result.items;
                //guanjds_curr = new HKP_ToolDto[] { cbJT.SelectedItem as HKP_ToolDto };
                //始终显示全部机台图形
                //guanjds_curr = cbJT.Items.Cast<HKP_ToolDto>().ToArray();// new HKP_ToolDto[] { cbJT.SelectedItem as HKP_ToolDto };
                //过滤当前楼层
                var sltFloor = (floor.SelectedItem as HKP_CategoryDto)?.CateName?.ToString();
                guanjds_curr = guanjds_curr.Where(a => a.Floor == sltFloor).ToArray();
                foreach (HKP_ToolDto item in guanjds_curr)
                {
                    var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "机台");
                    if (typeitem == null) continue;

                    if (typeitem.EleList != null)
                    {
                        var EleList = typeitem.EleList;
                        //var x1 = (int)EleList.Min(a => a.LocX);
                        //var x2 = (int)EleList.Max(a => a.LocX + a.SizeWidth);
                        //var y1 = (int)EleList.Min(a => a.LocY);
                        //var y2 = (int)EleList.Max(a => a.LocY + a.SizeHeight);

                        var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
                        var x2 = (int)EleList.Max(a => Math.Max(a.LocX, a.LocX2));
                        var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
                        var y2 = (int)EleList.Max(a => Math.Max(a.LocY, a.LocY2));

                        var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                        if (rtshape.Width <= 0 || rtshape.Height <= 0) continue;

                        //仅仅操作副本
                        var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();

                        #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
                        foreach (var ele in elelist)
                        {
                            ele.LocX -= rtshape.X;
                            ele.LocY -= rtshape.Y;
                            ele.LocX2 -= rtshape.X;
                            ele.LocY2 -= rtshape.Y;
                            ele.Control_1_X -= rtshape.X;
                            ele.Control_1_Y -= rtshape.Y;

                            var scaleX = (double)item.Width / (double)rtshape.Width;
                            var scaleY = (double)item.Length / (double)rtshape.Height;

                            ele.LocX *= scaleX;
                            ele.LocX2 *= scaleX;
                            ele.LocY *= scaleY;
                            ele.LocY2 *= scaleY;
                            ele.Control_1_X *= scaleX;
                            ele.Control_1_Y *= scaleY;
                        }
                        #endregion

                        //图形的容器控件 

                        var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
                        var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
                        var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
                        var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));

                        var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, xMax - xMin + 1, yMax - yMin + 1);
                        //由中心点向四向扩展
                        //rtContainer.Offset(-rtContainer.Width / 2, -rtContainer.Height / 2); 

                        //始终显示在画布中心
                        //item.X = (int)(DrawShow.split_arr_col.Sum() / 2 - rtContainer.Width / 2);
                        //item.Y = (int)(DrawShow.split_arr_row.Sum() / 2 - rtContainer.Height / 2);

                        //+边缘距离
                        rtContainer.X += DrawShow.drawEdge_hor;
                        rtContainer.Y += DrawShow.drawEdge_ver;
                        //创建容器
                        var cvNew = DrawShow.doAddDrawEleContainer_Guandao(rtContainer);
                        cvNew.RenderTransformOrigin = new System.Windows.Point(0, 0);
                        cvNew.RenderTransform = DrawShow.GetYFlipTrans1And1();
                        //列表转化
                        //item.SubmainName = lst_guandao.result?.items?.FirstOrDefault(a => a.SubmainNo == item.SubmainNo)?.SubmainName;
                        cvNew.ToolTip = new UC_Tooltip_Jiitai(item);
                        System.Windows.Controls.ToolTipService.SetShowDuration(cvNew, 10000);
                        //区域的快捷菜单
                        //container_Quyu_Menu(cvNew, item);
                        //子元素放入到父容器中
                        foreach (var ele in elelist)
                        {
                            DrawShow.doAddDrawEleControl(ele, cvNew);
                        }
                        //添加文本说明
                        //DrawShow.doAddDrawEleContainer_Desc_Jitai(cvNew, item.ToolName);
                        DrawShow.doAddDrawEleContainer_Desc_Jitai(cvNew, item.EquipmentID);
                        ////加载区域内节点
                        //loadChildInArea(cvNew, comboBoxSys.SelectedValue?.ToString(), item.Id);

                    }
                }
            }
            #endregion

        }
        


        private void BindCombSys()
        {
            ItemsDto<HKP_SystemDto> dto = lst_system;
            comboBoxSys.DataSource = dto?.result?.items;
            comboBoxSys.DisplayMember = "SysName";
            comboBoxSys.ValueMember = "SysName";
        }

        private void BuildingSelectedChange(object sender, EventArgs e)
        {
            BindCombSys();
        }

        private void checkDrawInit()
        {
            Invoke((ThreadStart)delegate
            {
                if (DrawShow == null)
                {
                    ElementHost eh = new ElementHost() { Dock = DockStyle.Fill };
                    DrawShow = new UC_DrawShow() { ParentLayout = this };
                    DrawShow.DrawBgMouseMoveAction = FormMain.Instance.DrawBgMouseMoveAction;
                    DrawShow.refreshDataAction = () =>
                    {
                        RefreshData();
                        bindCacheDataToUI();
                    };
                    DrawShow.refreshDataJiedianAction = () =>
                    {
                        Refresh_Jiedian();
                        BindUI_Draw();
                    };
                    DrawShow.refreshDataQuyuAction = () =>
                    {
                        Refresh_Quyu();
                        BindUI_Draw();
                    };
                    DrawShow.refreshDataGuandaoAction = () =>
                    {
                        Refresh_Guandao();
                        BindUI_Draw();
                    };
                    DrawShow.refreshDrawAction = () =>
                    {
                        DrawShow.ClearDrawList();
                        GetFoorDrawingCache();
                        BindUI_Draw();
                    };
                    eh.Child = DrawShow;
                    panelS.Controls.Add(eh);
                }
            });
        }

        /// <summary>
        ///当前楼层对应的绘图信息
        /// </summary>
        private void GetFoorDrawingCache()
        {
            //画图展示区域  
            var key = building.SelectedValue?.ToString() + "_" + floor.SelectedValue?.ToString();
            DrawShow.DrawingCacheInfo = LocalDataHelper.GetFloorDrawingInfo(
                new System.Windows.Controls.UserControl(), key);

            if (DrawShow.DrawingCacheInfo == null) DrawShow.DrawingCacheInfo = new FloorDrawingInfo()
            {
                uid = key,
            };

            DrawShow.DrawingCacheInfo.id_building = building.SelectedValue?.ToString();
            DrawShow.DrawingCacheInfo.id_floor = floor.SelectedValue?.ToString();
            DrawShow.DrawingCacheInfo.text_building = (building.SelectedItem as HKP_CategoryDto).CateName;
            DrawShow.DrawingCacheInfo.text_floor = (floor.SelectedItem as HKP_CategoryDto).CateName;

            DrawShow.ResetBgDrawing();
        }

        private void BindDataGridSource()
        {
            //LoadHDC();
            LoadHKPTool("");
        }


        private void container_Quyu_Menu(System.Windows.Controls.Canvas cvnew, object datacontext)
        {
            var cm = new System.Windows.Controls.ContextMenu();

            var mi = new System.Windows.Controls.MenuItem() { Header = "区块详情", Tag = datacontext };
            mi.PreviewMouseRightButtonDown += Mi_PreviewMouseRightButtonDown;
            mi.Click += Mi_Click;
            cm.Items.Add(mi);

            //mi = new System.Windows.Controls.MenuItem() { Header = "派点", Tag = datacontext };
            //mi.PreviewMouseRightButtonDown += Mi_PreviewMouseRightButtonDown;
            //mi.Click += Mi_Click1;
            //cm.Items.Add(mi);

            mi = new System.Windows.Controls.MenuItem() { Header = "添加接点", Tag = datacontext };
            mi.PreviewMouseRightButtonDown += Mi_PreviewMouseRightButtonDown;
            mi.Click += Mi_Click2;
            cm.Items.Add(mi);


            mi = new System.Windows.Controls.MenuItem() { Header = "添加管道", Tag = datacontext };
            mi.PreviewMouseRightButtonDown += Mi_PreviewMouseRightButtonDown;
            mi.Click += Mi_Click4;
            cm.Items.Add(mi);

            cvnew.ContextMenu = cm;
        }

        private void container_Jiedian_Menu(System.Windows.Controls.Canvas cvnew, object datacontext)
        {
            var cm = new System.Windows.Controls.ContextMenu();

            var mi = new System.Windows.Controls.MenuItem() { Header = "属性", Tag = datacontext };
            mi.PreviewMouseRightButtonDown += Mi_PreviewMouseRightButtonDown;
            mi.Click += Mi_Click3;
            cm.Items.Add(mi);

            mi = new System.Windows.Controls.MenuItem() { Header = "派点", Tag = datacontext };
            mi.PreviewMouseRightButtonDown += Mi_PreviewMouseRightButtonDown;
            mi.Click += Mi_Click1;
            cm.Items.Add(mi);


            cvnew.ContextMenu = cm;
        }


        #endregion


        #region 事件

        private void PanelS_SizeChanged(object sender, EventArgs e)
        {
            if (DrawShow != null) DrawShow.ShowMapAll();
        }

        private void UC_SysLayout_Load(object sender, EventArgs e)
        {
            client = new APIClient(webAPI);
            checkDrawInit();

            //系统下拉
            GetSystem("System",0);


            //异步数据处理
            Task.Run(delegate
            {
                Thread.Sleep(100);

                //加载数据
                RefreshData(true);

                //控件事件绑定
                Invoke((ThreadStart)delegate
                {
                    try
                    {
                        building.SelectedIndexChanged -= Building_SelectedIndexChanged;
                        floor.SelectedIndexChanged -= Floor_SelectedIndexChanged;
                        //comboBoxSys.SelectedIndexChanged -= ComboBoxSys_SelectedIndexChanged;
                        comboBoxSys.SelectionChangeCommitted += comboBoxSys_SelectionChangeCommitted;
                        cbEquipe.SelectedIndexChanged -= JTEquip_SelectedIndexChanged;
                        cbJT.SelectedIndexChanged -= CbJT_SelectedIndexChanged;
                      

                        bindCacheDataToUI();

                        building.SelectedIndexChanged += Building_SelectedIndexChanged;
                        floor.SelectedIndexChanged += Floor_SelectedIndexChanged;
                        //comboBoxSys.SelectedIndexChanged += ComboBoxSys_SelectedIndexChanged;
                        comboBoxSys.SelectionChangeCommitted += comboBoxSys_SelectionChangeCommitted;
                        comboBoxSys.KeyPress += ComboBoxSys_KeyPress;
                        numFitDistence.KeyPress += ComboBoxSys_KeyPress;
                        cbEquipe.SelectedIndexChanged += JTEquip_SelectedIndexChanged;
                        cbJT.SelectedIndexChanged += CbJT_SelectedIndexChanged;

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                });
            });
        }

        public void GetSystem(string layout, int parentId)
        {
            string url = string.Format("api/services/app/HKP_Category/GetList?layout={0}&parentId={1}", layout, parentId);
            APIClient client = new APIClient(webAPI);
            var result = client.Get(url);
            ItemsDto<HKP_CategoryDto> res = JsonConvert.DeserializeObject<ItemsDto<HKP_CategoryDto>>(result);
            comboBoxSysType.DisplayMember = "cateName";
            comboBoxSysType.ValueMember = "cateName";
            comboBoxSysType.DataSource = res?.result?.items;
            comboBoxSysType.SelectedIndex = -1;
        }




        /// <summary>
        /// 机台下拉框改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CbJT_SelectedIndexChanged(object sender, EventArgs e)
        {
            var system = comboBoxSystem.SelectedItem as HKP_SystemDto;
            var Tool = cbJT.SelectedItem as HKP_ToolDto;
            if (Tool == null) return;
            Task.Run(delegate
            {
                Thread.Sleep(50);
                try
                {
                    HKP_ToolSysReqDto[] sysReqArr = lst_jt_sys.result?.items?.Where(a => a.ToolId == Tool.Id).ToArray();
                    //如果选择了系统，根据系统过滤接点
                    
                    //if (!string.IsNullOrEmpty(system.SysNo))
                    if(system != null)
                    {
                        sysReqArr= lst_jt_sys.result?.items?.Where(a => a.ToolId == Tool.Id && a.SysNo==system.SysNo).ToArray();
                    }

                    
                    Invoke((ThreadStart)delegate
                    {
                        comboBoxSys.DisplayMember = "Name";
                        comboBoxSys.ValueMember = "Id";
                        comboBoxSys.DataSource = sysReqArr;
                        comboBoxSys.SelectedIndex = -1;

                        //这是重新画comboxsys控件，已经派点的显示红色
                        comboBoxSys.DrawMode = DrawMode.OwnerDrawFixed;

                        //comboBoxSys.Items.AddRange(x);

                        //if (sysReqArr.Any())
                        //    comboBoxSys.SelectedIndex = 0;
                    });
                }
                catch (Exception ex)
                {
                }
            });
        }
        //private HKP_ToolSysReqDto[] GetToolSysReq(string toolId)
        //{
        //    return lst_jt_sys.result?.items?.Where(a => a.ToolId == toolId).ToArray();
        //    //string url = string.Format(apiSysReq + "GetList?toolId={0}", toolId);
        //    //var result = client.Get(url);
        //    //ItemsDto<HKP_ToolSysReqDto> dto = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolSysReqDto>>(result);
        //    //return dto.result.items;
        //}


        private void ComboBoxSys_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (Char)Keys.Enter) ReDraw();
        }

        private void comboBoxSys_SelectionChangeCommitted(object sender, EventArgs e)
        {
            //var sysitem = comboBoxSys.SelectedItem as HKP_ToolSysReqDto;
            //if (sysitem == null)
            //{
            //    return;
            //}
            Task.Run(delegate
            {
                Thread.Sleep(50);
                Invoke((ThreadStart)delegate
                {
                    ReDraw();
                });
            });
        }

        private void Floor_SelectedIndexChanged(object sender, EventArgs e)
        {
            Task.Run(delegate
            {
                //Thread.Sleep(50);
                Invoke((ThreadStart)delegate
                {
                    cbEquipe.SelectedIndexChanged -= JTEquip_SelectedIndexChanged;
                    cbJT.SelectedIndexChanged -= CbJT_SelectedIndexChanged;

                    //过滤机台设备组
                    FilterJitaiEquipByFloor();
                    //过滤机台
                    FilterJitaiByFloorAndEquip();


                    cbEquipe.SelectedIndexChanged += JTEquip_SelectedIndexChanged;
                    cbJT.SelectedIndexChanged += CbJT_SelectedIndexChanged;


                    //重新绘制
                    ReDraw();
                });
            });
        }
        private void JTEquip_SelectedIndexChanged(object sender, EventArgs e)
        {
            Task.Run(delegate
            {
                //Thread.Sleep(50);
                Invoke((ThreadStart)delegate
                {
                    cbJT.SelectedIndexChanged -= CbJT_SelectedIndexChanged;

                    //过滤机台
                    FilterJitaiByFloorAndEquip();

                    cbJT.SelectedIndexChanged += CbJT_SelectedIndexChanged;

                    //重新绘制
                    //ReDraw();
                });
            });
        }

        private void Building_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                var sltid = long.Parse(building.SelectedValue.ToString());
                floor.DataSource = lst_buildfloor.result.items.Where(a => a.ParentId == sltid).ToList();
                floor.DisplayMember = "CateName";
                floor.ValueMember = "Id";
            }
            catch (Exception)
            {

            }
        }

        private void FloorSelectedChange(object sender, EventArgs e)
        {
            //GetBlocks();
            //GetDrawingCache(); 
            //DrawShow?.refreshDrawAction?.Invoke();
        }



        private void dgvTool_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //if (e.RowIndex < 0) return;

            //HKP_ToolDto dto = dgvTool.Rows[e.RowIndex].DataBoundItem as HKP_ToolDto;
            //机台编辑窗口
            //FormTool formEdit = new FormTool(dto, client);
            //if (formEdit.ShowDialog() == DialogResult.OK)
            //{
            //    RefreshData();
            //    BindUI_Draw();
            //}
        }


        /// <summary>
        /// 查看接点属性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mi_Click3(object sender, System.Windows.RoutedEventArgs e)
        {

            //二次配旋前
            string[] str = main.user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！您不能派点，请联系管理员！");
                return;
            }


            var dto = (sender as System.Windows.Controls.MenuItem).Tag as HKP_TakeoffDto;
            FormTakeOff form = new FormTakeOff(dto, client);
            form.ShowDialog();
        }

        /// <summary>
        /// 添加接点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mi_Click2(object sender, System.Windows.RoutedEventArgs e)
        {
            string[] str = main.user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！您不能派点，请联系管理员！");
                return;
            }
            if (DrawShow == null) return;

            var block = (sender as System.Windows.Controls.MenuItem).Tag as HKP_BlockDto;
            //获取当前鼠标点 
            FormTakeOff form = new FormTakeOff(null, client, block.Id, currentX, currentY);
            Task.Run(delegate
            {
                Thread.Sleep(500);
                Invoke((ThreadStart)delegate
                {
                    try
                    {
                        form.SetLoc(DrawShow.mouseDownX_Draw, DrawShow.mouseDownY_Draw);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("该位置不可添加接点！");
                    }
                });
            });

            form.ShowDialog();


            Refresh_Jiedian();
            BindUI_Draw();

        }

        /// <summary>
        /// 添加管道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mi_Click4(object sender, System.Windows.RoutedEventArgs e)
        {
            string[] str = main.user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！您不能派点，请联系管理员！");
                return;
            }
            if (DrawShow == null) return;

            var block = (sender as System.Windows.Controls.MenuItem).Tag as HKP_BlockDto;
            //获取当前鼠标点 
            FormSubmain form = new FormSubmain(null, client);
            Task.Run(delegate
            {
                Thread.Sleep(500);
                Invoke((ThreadStart)delegate
                {
                    try
                    {
                        form.SetLoc(DrawShow.mouseDownX_Draw, DrawShow.mouseDownY_Draw);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("该位置不可添加管道！");
                    }
                });
            });

            form.ShowDialog();

            Refresh_Guandao();
            BindUI_Draw();

        }


        /// <summary>
        /// 派点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mi_Click1(object sender, System.Windows.RoutedEventArgs e)
        {
            //二次配旋前
            string[] str =main.user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！您不能派点，请联系管理员！");
                return;
            }

            //判断是否有派点权限

            HKP_TakeoffDto currentTakeoff = (sender as System.Windows.Controls.MenuItem).Tag as HKP_TakeoffDto;
            HKP_BlockDto currBlock = lst_block.result?.items?.FirstOrDefault(a => a.Id == currentTakeoff.BlockId);
            HKP_ToolDto currentTool = cbJT.SelectedItem as HKP_ToolDto;

            //如果机台文号是空，则不允许派点，因为未送审
            if (string.IsNullOrEmpty(currentTool.SignatureNo))
            {
                MessageBox.Show("该机台未审核，请先审核再进行派点！");
                return;
            }


            if (!jiedian_canp.Contains(currentTakeoff))
            {
                MessageBox.Show("该接点不可派点！");
                return;
            }

            if (currentTool == null)
            {  
                MessageBox.Show("请选择机台！");
                return;
            }
            //接点信息
            var sysitem = comboBoxSys.SelectedItem as HKP_ToolSysReqDto;
            if (sysitem.SysNo == "ES")
            {
                if (currentTakeoff.PointType == "1")
                {
                    //电盘派点一次占用一个管道的接点
                    //string act1 = client.Post(apiSubmain + "UsedSubmainPoint?id=" + currentTakeoff.SubmainId + "&x=1", "");
                    //ErrorObject ret = Utils.ExceptionHandler(act1);
                    //查询HDC是否是重复的扣除，一个接点第一次派到电盘上才扣出容量
                    ItemsDto<HKP_HDCDto> listhdcsysno = new ItemsDto<HKP_HDCDto>();
                    if (!string.IsNullOrEmpty(sysitem.SysNo))
                    {
                        string url = string.Format(apiHDC + "GetList?skipCount={0}&maxResultCount={1}&&keyWords={2}&building={3}&floor={4}&fabArea={5}&sysNo={6}", 0, 9999, "", "", "", "", sysitem.SysNo);
                        var result = client.Get(url);
                        listhdcsysno = JsonConvert.DeserializeObject<ItemsDto<HKP_HDCDto>>(result);
                    }
                    bool goon = false;
                    if (listhdcsysno?.result?.items != null)
                    {
                        foreach (var itemhdcno in listhdcsysno.result.items)
                        {
                            if (itemhdcno.ToolSysReqId== sysitem.Id)
                            {
                                goon = true;
                            }
                        }
                    }
                    if (!goon)
                    {
                        //算出机台的容量
                        double toolRongL = Utils.ToInA(sysitem.FlowPeak.ToString(), sysitem.FlowUnit);//机台负荷算出安培
                        if (toolRongL <= 0)
                        {
                            toolRongL = Utils.ToInA(sysitem.Power.ToString(), sysitem.PowerUnit);//功率算出安培
                        }
                        //扣除管道的容量
                        string act2 = client.Put(apiSubmain + "upDateUsedflow?id=" + currentTakeoff.SubmainId + "&x=0&usedflow="+toolRongL+"", "");
                        ErrorObject ret1 = Utils.ExceptionHandler(act2);
                    }
                }
               
            }



            try
            {
                ////对该接点进行派点
                var rst = Do_Paidian.paidian(client, currentTakeoff, currBlock, currentTool, comboBoxSys.SelectedValue.ToString());
                ////FormSelTakeOff form = new FormSelTakeOff(client, currentBlock, currentTool);
                if (rst)
                {
                    lst_guandao = null;
                    lst_takeoff = null;

                    //刷新数据 
                    Refresh_Guandao();
                    Refresh_Jiedian();
                    BindUI_Draw();
                    //走线程比较慢
                    //Task.Run(delegate
                    //{
                    //    Refresh_Guandao();
                    //    Refresh_Jiedian();
                    //    Invoke((ThreadStart)delegate
                    //    {
                    //        BindUI_Draw();
                    //    });
                    //});
                }
                else
                {
                    //MessageBox.Show("派点失败,请检查：接口尺寸大小");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("派点失败！---"+ex.Message);
            }

        }


        /// <summary>
        /// 右键快捷菜单 - 区块详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Mi_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            string[] str = main.user[0].RoleNames;
            int a = str.Count(p => p == "ADMIN" || p == "DESIGNER");
            if (a <= 0)
            {
                Utils.SysMsg("对不起！您不能派点，请联系管理员！");
                return;
            }
            var block = (sender as System.Windows.Controls.MenuItem).Tag as HKP_BlockDto;
            FormBlock form = new FormBlock(block, client, "", "");
            form.ShowDialog();

        }

        private void Mi_PreviewMouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            //禁止处理下层元素事件
            e.Handled = true;
        }



        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            //FormMain main=new FormMain();
            HKP_ToolDto dto = cbJT.SelectedItem as HKP_ToolDto;
            if (dto == null) return;
            //机台编辑窗口
            FormTool formEdit = new FormTool(dto, client,main);
            if (formEdit.ShowDialog() == DialogResult.OK)
            {
                RefreshData();
                BindUI_Draw();
            }
        }

        private void comboBoxSys_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index == -1) { return; }
            ComboBox cbo = sender as ComboBox;

            //初始化字体和背景色
            Pen fColor = new Pen(Color.Black);
            Pen bColor = new Pen(Color.White);
            bool type = ((HKP_ToolSysReqDto)comboBoxSys.Items[e.Index]).isPaiDian;
            if (type == true)
            {
                fColor = new Pen(Color.Red);
                //switch (e.Index)
                //{     //下拉选项的索引
                //    case 1:
                //        {
                //            //if (((HKP_ToolSysReqDto)comboBoxSys.Items[e.Index]).isPaiDian)
                //            //{
                //            //    fColor = new Pen(Color.Red);
                //            //}
                //            //else
                //            //{
                //            //    fColor = new Pen(Color.Green);
                //            //}
                //            fColor = new Pen(Color.Red);
                //            break;
                //        }
                //}
            }


            e.DrawBackground();
            e.Graphics.FillRectangle(bColor.Brush, e.Bounds);
            e.Graphics.DrawString(((HKP_ToolSysReqDto)comboBoxSys.Items[e.Index]).Name, this.Font, fColor.Brush, e.Bounds);
        }
        
        //根据详细分类筛选出的设备ID的下拉框的改变事件
        private void CbEquipe_SelectionChangeCommitted(object sender,EventArgs e)
        {
            var system = comboBoxSystem.SelectedItem as HKP_SystemDto;
            var sltFloor = (floor.SelectedItem as HKP_CategoryDto)?.CateName?.ToString();
            var slt_equpid = cbEquipe.SelectedItem?.ToString();

            var lst_tool_floor = SysLst_tool?.result?.items.Where(a => a.Floor == sltFloor).ToArray();

            cbJT.DataSource = null;
            cbJT.Items.Clear();
            cbJT.Text = "";
            //机台按照
            //cbJT.DataSource = lst_tool_floor.Where(a => a.EquipmentID == slt_equpid).ToList();
            //cbJT.DisplayMember = "ToolName";
            //cbJT.ValueMember = "ToolId";
            //cbJT.SelectedIndex = -1;
            
        }



        //详细分类下拉事件
        private void comboBoxSystem_SelectionChangeCommitted(object sender,EventArgs e)
        {
            var system = comboBoxSystem.SelectedItem as HKP_SystemDto;


            //ItemsDto<HKP_ToolDto> res_jt = lst_tool;//机台的缓存数据
            var name_block = building.Text;//厂区
            var name_floor = floor.Text;//楼层

            
          
            //根绝选择的详细类型查出所在楼层该系统所有的机台
            string url = string.Format("api/services/app/HKP_Tool/GetToolFromSysNo?sysno={0}&building={1}&floor={2}", system.SysNo,name_block, name_floor);
            APIClient client = new APIClient(webAPI);
            var result = client.Get(url);
            SysLst_tool = JsonConvert.DeserializeObject<ItemsDto<HKP_ToolDto>>(result);
            HKP_ToolDto[] list = SysLst_tool.result?.items.ToArray();

            cbEquipe.Items.Clear();
            cbEquipe.Text = "";
            if ((SysLst_tool?.result?.items).Any())
            {
                 var eqlist = list.Select(a => a.EquipmentID).Distinct().ToArray();
                 cbEquipe.Items.AddRange(eqlist);
            }
            //重新绑定下拉框改变事件
            cbEquipe.SelectionChangeCommitted += CbEquipe_SelectionChangeCommitted;
            //清空机台
            cbJT.DataSource = null;
            cbJT.Items.Clear();
            cbJT.Text = "";
            //清空接点
            comboBoxSys.DataSource = null;
            comboBoxSys.Items.Clear();
            comboBoxSys.Text = "";




            Task.Run(delegate
            {
                //刷新接点数据 
                //Refresh_Jiedian();
                Invoke((ThreadStart)delegate
                {
                    //BindUI_DrawLoadjiedianandgudandao("", false, system.SysNo);
                    BindUI_Draw1("", false, system.SysNo);
                });
            });


        }

        //主系统下拉事件
        private void comboBoxSysType_SelectionChangeCommitted(object sender, EventArgs e)
        {
            string sysNo = comboBoxSysType.SelectedValue.ToString();
            //画出所有接点
            BindUI_Draw1(sysNo,true,"");
            string url = string.Format("api/services/app/HKP_System/GetListSysNo?keywords={0}", sysNo);
            APIClient client = new APIClient(webAPI);
            var result = client.Get(url);
            ItemsDto<HKP_SystemDto> res1 = JsonConvert.DeserializeObject<ItemsDto<HKP_SystemDto>>(result);
            //赋值给详细下拉
            comboBoxSystem.DisplayMember = "SysNo";
            comboBoxSystem.ValueMember = "SysNo";
            comboBoxSystem.DataSource = res1.result?.items;
            comboBoxSystem.SelectedIndex = -1;
            //给出下拉框选择改变事件
            comboBoxSystem.SelectionChangeCommitted += comboBoxSystem_SelectionChangeCommitted;

            //清空cbEquipe下拉
            cbEquipe.Items.Clear();
            cbEquipe.Text = "";


            //foreach (var item1 in res1.result?.items)
            //{


            //}
            //

        }

        private void BindUI_Draw1(string sysNo,bool usedSystemType,string SystemNo)
        {
            DrawShow.ClearDrawList();
            jiedianui_type_ui.Clear();
            jiedianui_type_ui_brush.Clear();
            jiedian_canp.Clear();
            

            //清除信息
            jiedian_lst_curr = null;

            var name_block = building.Text;
            var name_floor = floor.Text;


            //机台半径附近 
            BindUI_Draw_JTRound();

            string url = string.Format("api/services/app/HKP_System/GetListSysNo?keywords={0}", sysNo);
            APIClient client = new APIClient(webAPI);
            var result = client.Get(url);
            ItemsDto<HKP_SystemDto> res1 = JsonConvert.DeserializeObject<ItemsDto<HKP_SystemDto>>(result);
          

            #region 区域 + 接点
            ItemsDto<HKP_BlockDto> res = lst_block;
            if (res != null && res.result != null)
            {
                //var sysitem = comboBoxSys.SelectedItem as HKP_ToolSysReqDto;
                var blocks_curr = res.result.items;
                blocks_curr = blocks_curr.Where(a => a.Building == name_block && a.Floor == name_floor).ToArray();
                foreach (HKP_BlockDto item in blocks_curr)
                {
                    var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "区域");
                    if (typeitem == null) continue;

                    if (typeitem.EleList != null)
                    {
                        var EleList = typeitem.EleList;

                        var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
                        var x2 = (int)EleList.Max(a => Math.Max(a.LocX, a.LocX2));
                        var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
                        var y2 = (int)EleList.Max(a => Math.Max(a.LocY, a.LocY2));

                        var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                        if (rtshape.Width <= 0 || rtshape.Height <= 0) continue;

                        //仅仅操作副本
                        var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();

                        #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
                        foreach (var ele in elelist)
                        {
                            ele.LocX -= rtshape.X;
                            ele.LocY -= rtshape.Y;
                            ele.LocX2 -= rtshape.X;
                            ele.LocY2 -= rtshape.Y;
                            ele.Control_1_X -= rtshape.X;
                            ele.Control_1_Y -= rtshape.Y;

                            var scaleX = (double)item.Width / (double)rtshape.Width;
                            var scaleY = (double)item.Length / (double)rtshape.Height;

                            ele.LocX *= scaleX;
                            ele.LocX2 *= scaleX;
                            ele.LocY *= scaleY;
                            ele.LocY2 *= scaleY;
                            ele.Control_1_X *= scaleX;
                            ele.Control_1_Y *= scaleY;
                        }
                        #endregion

                        //图形的容器控件 
                        var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
                        var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
                        var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
                        var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));
                        var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, xMax - xMin + 1, yMax - yMin + 1);
                        //+边缘距离
                        rtContainer.X += DrawShow.drawEdge_hor;
                        rtContainer.Y += DrawShow.drawEdge_ver;
                        //创建容器
                        var cvNew = DrawShow.doAddDrawEleContainer_Quyu(rtContainer);
                        //区域的快捷菜单
                        container_Quyu_Menu(cvNew, item);
                        //子元素放入到父容器中
                        foreach (var ele in elelist)
                        {
                            DrawShow.doAddDrawEleControl(ele, cvNew);
                        }
                        //添加文本说明
                        DrawShow.doAddDrawEleContainer_Desc_Quyu(cvNew, item.BlockName);

                        //加载区域内节点 
                        if (usedSystemType)
                        {
                            foreach (var item1 in res1.result?.items)
                            {

                                loadChildInAreaFromCache1(DrawShow.cvDrawMain, item1.SysNo, item.Id);
                            }
                        }
                        else
                        {
                            loadChildInAreaFromCache1(DrawShow.cvDrawMain, SystemNo, item.Id);
                        }
                       
                        

                    }
                    //元素事件处理
                }
            }

            #endregion

            #region 管道 
            ItemsDto<HKP_SubmainDto> res_gd = lst_guandao;
            //var currentSys = comboBoxSys.Text;
            var currentSys = "";
            if (usedSystemType)
            {
                foreach (var item1 in res1.result?.items)
                {
                    if (item1.SysNo == "D-Ag")
                    {

                    }

                    currentSys = item1.SysNo;
                    if (res_gd != null && res_gd.result != null)
                    {
                        //当前所选的系统编号
                        var sysReqArr = lst_jt_sys.result?.items?.ToArray();
                        var sltsysid = comboBoxSys.SelectedValue?.ToString();
                        //currentSys = sysReqArr.FirstOrDefault(a => a.Id.ToString() == sltsysid)?.SysNo;

                        var guandaos_curr = res_gd.result.items;
                        //过滤系统 不指定系统时，不加载管道
                        if (!string.IsNullOrEmpty(currentSys))
                        {
                            guandaos_curr = guandaos_curr.Where(o => o.SysNo == currentSys).ToArray();
                        }
                        else guandaos_curr = new HKP_SubmainDto[0];
                        //过滤楼层、建筑 
                        var floor_slt = (floor.SelectedItem as HKP_CategoryDto)?.CateName?.ToString();
                        var building_slt = (building.SelectedItem as HKP_CategoryDto).CateName;
                        guandaos_curr = guandaos_curr?.Where(a => a.Floor == floor_slt && a.Building == building_slt).ToArray();


                        foreach (HKP_SubmainDto item in guandaos_curr)
                        {
                            var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "管道" && a.BindDataProperty == item.SysNo);
                            //if (typeitem == null) typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "管道");
                            if (typeitem == null) continue;

                            if (typeitem.EleList != null)
                            {
                                var EleList = typeitem.EleList;
                                //var x1 = (int)EleList.Min(a => a.LocX);
                                //var x2 = (int)EleList.Max(a => a.LocX + a.SizeWidth);
                                //var y1 = (int)EleList.Min(a => a.LocY);
                                //var y2 = (int)EleList.Max(a => a.LocY + a.SizeHeight);

                                var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
                                var x2 = (int)EleList.Max(a => Math.Max(a.LocX, a.LocX2));
                                var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
                                var y2 = (int)EleList.Max(a => Math.Max(a.LocY, a.LocY2));

                                var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                                if (rtshape.Width <= 0 || rtshape.Height <= 0) continue;

                                //仅仅操作副本
                                var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();


                                #region 管道颜色控制
                                //管道图形绑定了管道业务数据，能够实时展现管道流量状况（正常流量显示蓝色、超过阈值显示红色）。
                                //计算方式：
                                //此管道业务数据里面的操作流量和此管道所有接点业务数据的操作流量之和做对比，大于则此管道显示红色，正常则显示蓝色
                                var parentFlow = item.FlowPeakOperation;

                                bool usedyellow = item.usedpoint >= item.Allpoint * 0.8;//超过80%的接点已使用 管道画黄色
                                bool usedred = item.usedpoint >= item.Allpoint * 0.95;//超过95的接点使用

                                bool yellowFlow=Convert.ToDouble(item.numUsedFlow)>Convert.ToInt32(item.FlowPeak)*0.8;
                                bool redFlow = Convert.ToDecimal(item.numUsedFlow) > item.FlowPeak;



                                //该管道关联的所有接点的操作流量之和
                                //var childlist = lst_takeoff.result.items.Where(a => a.SubmainName == item.SubmainName).ToList();
                                //decimal childFlowSum = 0;
                                //if (childlist.Any())
                                //    childFlowSum = childlist.Sum(a => a.FlowPeakOperation);
                                //System.Windows.Media.SolidColorBrush bsRst = System.Windows.Media.Brushes.Blue;
                                //if (parentFlow > childFlowSum) 
                                //    bsRst = System.Windows.Media.Brushes.Red;
                                System.Windows.Media.SolidColorBrush bsRst = System.Windows.Media.Brushes.Blue;
                                if (usedyellow==true && usedred==false)
                                {
                                    bsRst = System.Windows.Media.Brushes.Yellow;
                                }
                                if (usedred==true)
                                {
                                    bsRst = System.Windows.Media.Brushes.Red;
                                }
                                if (yellowFlow == true)
                                {
                                    bsRst = System.Windows.Media.Brushes.Yellow;
                                }
                                if (redFlow == true)
                                {
                                    bsRst = System.Windows.Media.Brushes.Red;
                                }
                                

                                foreach (var ele in elelist)
                                {
                                    ele.Stroke = bsRst;
                                    ele.Fill = bsRst;
                                }
                                #endregion



                                #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
                                foreach (var ele in elelist)
                                {
                                    ele.LocX -= rtshape.X;
                                    ele.LocY -= rtshape.Y;
                                    ele.LocX2 -= rtshape.X;
                                    ele.LocY2 -= rtshape.Y;
                                    ele.Control_1_X -= rtshape.X;
                                    ele.Control_1_Y -= rtshape.Y;

                                    var scaleX = (double)item.Width / (double)rtshape.Width;
                                    var scaleY = (double)item.Length / (double)rtshape.Height;

                                    ele.LocX *= scaleX;
                                    ele.LocX2 *= scaleX;
                                    ele.LocY *= scaleY;
                                    ele.LocY2 *= scaleY;
                                    ele.Control_1_X *= scaleX;
                                    ele.Control_1_Y *= scaleY;
                                }
                                #endregion

                                //图形的容器控件
                                //var xMin = elelist.Min(a => a.LocX);
                                //var xMax = elelist.Max(a => a.LocX2);
                                //var yMin = elelist.Min(a => a.LocY);
                                //var yMax = elelist.Max(a => a.LocY2);

                                var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
                                var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
                                var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
                                var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));
                                //if (xMax - xMin + 1 <= 0 || yMax - yMin + 1 <= 0)
                                //{ 
                                //} 
                                var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, xMax - xMin + 1, yMax - yMin + 1);

                                //+边缘距离
                                rtContainer.X += DrawShow.drawEdge_hor;
                                rtContainer.Y += DrawShow.drawEdge_ver;
                                //创建容器
                                var cvNew = DrawShow.doAddDrawEleContainer_Guandao(rtContainer);
                                //列表转化
                                item.SubmainName = lst_guandao.result?.items?.FirstOrDefault(a => a.SubmainNo == item.SubmainNo)?.SubmainName;
                                cvNew.ToolTip = new UC_Tooltip_Guandao(item);
                                System.Windows.Controls.ToolTipService.SetShowDuration(cvNew, 10000);
                                //区域的快捷菜单
                                //container_Quyu_Menu(cvNew, item);
                                //子元素放入到父容器中
                                foreach (var ele in elelist)
                                {
                                    DrawShow.doAddDrawEleControl(ele, cvNew);
                                }
                                //添加文本说明
                                //DrawShow.doAddDrawEleContainer_Desc_Quyu(cvNew, item.SubmainName);

                                ////加载区域内节点
                                //loadChildInArea(cvNew, comboBoxSys.SelectedValue?.ToString(), item.Id);

                            }
                        }
                    }
                }
            }
            else
            {
                currentSys = SystemNo;
                if (res_gd != null && res_gd.result != null)
                {
                    //当前所选的系统编号
                    var sysReqArr = lst_jt_sys.result?.items?.ToArray();
                    var sltsysid = comboBoxSys.SelectedValue?.ToString();
                    //currentSys = sysReqArr.FirstOrDefault(a => a.Id.ToString() == sltsysid)?.SysNo;

                    var guandaos_curr = res_gd.result.items;
                    //过滤系统 不指定系统时，不加载管道
                    if (!string.IsNullOrEmpty(currentSys))
                    {
                        guandaos_curr = guandaos_curr.Where(o => o.SysNo == currentSys).ToArray();
                    }
                    else guandaos_curr = new HKP_SubmainDto[0];
                    //过滤楼层、建筑 
                    var floor_slt = (floor.SelectedItem as HKP_CategoryDto)?.CateName?.ToString();
                    var building_slt = (building.SelectedItem as HKP_CategoryDto).CateName;
                    guandaos_curr = guandaos_curr?.Where(a => a.Floor == floor_slt && a.Building == building_slt).ToArray();


                    foreach (HKP_SubmainDto item in guandaos_curr)
                    {
                        var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "管道" && a.BindDataProperty == item.SysNo);
                        //if (typeitem == null) typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "管道");
                        if (typeitem == null) continue;

                        if (typeitem.EleList != null)
                        {
                            var EleList = typeitem.EleList;
                            //var x1 = (int)EleList.Min(a => a.LocX);
                            //var x2 = (int)EleList.Max(a => a.LocX + a.SizeWidth);
                            //var y1 = (int)EleList.Min(a => a.LocY);
                            //var y2 = (int)EleList.Max(a => a.LocY + a.SizeHeight);

                            var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
                            var x2 = (int)EleList.Max(a => Math.Max(a.LocX, a.LocX2));
                            var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
                            var y2 = (int)EleList.Max(a => Math.Max(a.LocY, a.LocY2));

                            var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                            if (rtshape.Width <= 0 || rtshape.Height <= 0) continue;

                            //仅仅操作副本
                            var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();


                            #region 管道颜色控制
                            //管道图形绑定了管道业务数据，能够实时展现管道流量状况（正常流量显示蓝色、超过阈值显示红色）。
                            //计算方式：
                            //此管道业务数据里面的操作流量和此管道所有接点业务数据的操作流量之和做对比，大于则此管道显示红色，正常则显示蓝色
                            var parentFlow = item.FlowPeakOperation;

                            bool usedyellow = item.usedpoint >= item.Allpoint * 0.8;//超过80%的接点已使用 管道画黄色
                            bool usedred = item.usedpoint >= item.Allpoint * 0.95;//超过95的接点使用

                            //该管道关联的所有接点的操作流量之和
                            var childlist = lst_takeoff.result.items.Where(a => a.SubmainName == item.SubmainName).ToList();
                            decimal childFlowSum = 0;
                            if (childlist.Any())
                                childFlowSum = childlist.Sum(a => a.FlowPeakOperation);
                            System.Windows.Media.SolidColorBrush bsRst = System.Windows.Media.Brushes.Blue;
                            //if (parentFlow > childFlowSum) 
                            //    bsRst = System.Windows.Media.Brushes.Red;

                            if (usedyellow && !usedred)
                            {
                                bsRst = System.Windows.Media.Brushes.Yellow;
                            }
                            if (usedred)
                            {
                                bsRst = System.Windows.Media.Brushes.Red;
                            }

                            foreach (var ele in elelist)
                            {
                                ele.Stroke = bsRst;
                                ele.Fill = bsRst;
                            }
                            #endregion



                            #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
                            foreach (var ele in elelist)
                            {
                                ele.LocX -= rtshape.X;
                                ele.LocY -= rtshape.Y;
                                ele.LocX2 -= rtshape.X;
                                ele.LocY2 -= rtshape.Y;
                                ele.Control_1_X -= rtshape.X;
                                ele.Control_1_Y -= rtshape.Y;

                                var scaleX = (double)item.Width / (double)rtshape.Width;
                                var scaleY = (double)item.Length / (double)rtshape.Height;

                                ele.LocX *= scaleX;
                                ele.LocX2 *= scaleX;
                                ele.LocY *= scaleY;
                                ele.LocY2 *= scaleY;
                                ele.Control_1_X *= scaleX;
                                ele.Control_1_Y *= scaleY;
                            }
                            #endregion

                            //图形的容器控件
                            //var xMin = elelist.Min(a => a.LocX);
                            //var xMax = elelist.Max(a => a.LocX2);
                            //var yMin = elelist.Min(a => a.LocY);
                            //var yMax = elelist.Max(a => a.LocY2);

                            var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
                            var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
                            var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
                            var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));
                            //if (xMax - xMin + 1 <= 0 || yMax - yMin + 1 <= 0)
                            //{ 
                            //} 
                            var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, xMax - xMin + 1, yMax - yMin + 1);

                            //+边缘距离
                            rtContainer.X += DrawShow.drawEdge_hor;
                            rtContainer.Y += DrawShow.drawEdge_ver;
                            //创建容器
                            var cvNew = DrawShow.doAddDrawEleContainer_Guandao(rtContainer);
                            //列表转化
                            item.SubmainName = lst_guandao.result?.items?.FirstOrDefault(a => a.SubmainNo == item.SubmainNo)?.SubmainName;
                            cvNew.ToolTip = new UC_Tooltip_Guandao(item);
                            System.Windows.Controls.ToolTipService.SetShowDuration(cvNew, 10000);
                            //区域的快捷菜单
                            //container_Quyu_Menu(cvNew, item);
                            //子元素放入到父容器中
                            foreach (var ele in elelist)
                            {
                                DrawShow.doAddDrawEleControl(ele, cvNew);
                            }
                            //添加文本说明
                            //DrawShow.doAddDrawEleContainer_Desc_Quyu(cvNew, item.SubmainName);

                            ////加载区域内节点
                            //loadChildInArea(cvNew, comboBoxSys.SelectedValue?.ToString(), item.Id);

                        }
                    }

                }
            }




            #endregion



            #region 机台 
            ItemsDto<HKP_ToolDto> res_jt = lst_tool;
            if (res_jt != null && res_jt.result != null
                //&& cbJT.SelectedItem != null
                )
            {
                var guanjds_curr = res_jt.result.items;
                //guanjds_curr = new HKP_ToolDto[] { cbJT.SelectedItem as HKP_ToolDto };
                //始终显示全部机台图形
                //guanjds_curr = cbJT.Items.Cast<HKP_ToolDto>().ToArray();// new HKP_ToolDto[] { cbJT.SelectedItem as HKP_ToolDto };
                //过滤当前楼层
                var sltFloor = (floor.SelectedItem as HKP_CategoryDto)?.CateName?.ToString();
                guanjds_curr = guanjds_curr.Where(a => a.Floor == sltFloor).ToArray();
                foreach (HKP_ToolDto item in guanjds_curr)
                {
                    var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "机台");
                    if (typeitem == null) continue;

                    if (typeitem.EleList != null)
                    {
                        var EleList = typeitem.EleList;
                        //var x1 = (int)EleList.Min(a => a.LocX);
                        //var x2 = (int)EleList.Max(a => a.LocX + a.SizeWidth);
                        //var y1 = (int)EleList.Min(a => a.LocY);
                        //var y2 = (int)EleList.Max(a => a.LocY + a.SizeHeight);

                        var x1 = (int)EleList.Min(a => Math.Min(a.LocX, a.LocX2));
                        var x2 = (int)EleList.Max(a => Math.Max(a.LocX, a.LocX2));
                        var y1 = (int)EleList.Min(a => Math.Min(a.LocY, a.LocY2));
                        var y2 = (int)EleList.Max(a => Math.Max(a.LocY, a.LocY2));

                        var rtshape = new System.Drawing.Rectangle(x1, y1, x2 - x1 + 1, y2 - y1 + 1);
                        if (rtshape.Width <= 0 || rtshape.Height <= 0) continue;

                        //仅仅操作副本
                        var elelist = typeitem.EleList.Select(a => a.Clone() as DrawEleInfo).ToList();

                        #region 宽高等比例压缩   对应的图形可能与实际展示比例不同，需要填充到指定大小显示
                        foreach (var ele in elelist)
                        {
                            ele.LocX -= rtshape.X;
                            ele.LocY -= rtshape.Y;
                            ele.LocX2 -= rtshape.X;
                            ele.LocY2 -= rtshape.Y;
                            ele.Control_1_X -= rtshape.X;
                            ele.Control_1_Y -= rtshape.Y;

                            var scaleX = (double)item.Width / (double)rtshape.Width;
                            var scaleY = (double)item.Length / (double)rtshape.Height;

                            ele.LocX *= scaleX;
                            ele.LocX2 *= scaleX;
                            ele.LocY *= scaleY;
                            ele.LocY2 *= scaleY;
                            ele.Control_1_X *= scaleX;
                            ele.Control_1_Y *= scaleY;
                        }
                        #endregion

                        //图形的容器控件 

                        var xMin = elelist.Min(a => Math.Min(a.LocX, a.LocX2));
                        var xMax = elelist.Max(a => Math.Max(a.LocX, a.LocX2));
                        var yMin = elelist.Min(a => Math.Min(a.LocY, a.LocY2));
                        var yMax = elelist.Max(a => Math.Max(a.LocY, a.LocY2));

                        var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, xMax - xMin + 1, yMax - yMin + 1);
                        //由中心点向四向扩展
                        //rtContainer.Offset(-rtContainer.Width / 2, -rtContainer.Height / 2); 

                        //始终显示在画布中心
                        //item.X = (int)(DrawShow.split_arr_col.Sum() / 2 - rtContainer.Width / 2);
                        //item.Y = (int)(DrawShow.split_arr_row.Sum() / 2 - rtContainer.Height / 2);

                        //+边缘距离
                        rtContainer.X += DrawShow.drawEdge_hor;
                        rtContainer.Y += DrawShow.drawEdge_ver;
                        //创建容器
                        var cvNew = DrawShow.doAddDrawEleContainer_Guandao(rtContainer);
                        cvNew.RenderTransformOrigin = new System.Windows.Point(0, 0);
                        cvNew.RenderTransform = DrawShow.GetYFlipTrans1And1();
                        //列表转化
                        //item.SubmainName = lst_guandao.result?.items?.FirstOrDefault(a => a.SubmainNo == item.SubmainNo)?.SubmainName;
                        cvNew.ToolTip = new UC_Tooltip_Jiitai(item);
                        System.Windows.Controls.ToolTipService.SetShowDuration(cvNew, 10000);
                        //区域的快捷菜单
                        //container_Quyu_Menu(cvNew, item);
                        //子元素放入到父容器中
                        foreach (var ele in elelist)
                        {
                            DrawShow.doAddDrawEleControl(ele, cvNew);
                        }
                        //添加文本说明
                        //DrawShow.doAddDrawEleContainer_Desc_Jitai(cvNew, item.ToolName);//按机台名称显示
                        DrawShow.doAddDrawEleContainer_Desc_Jitai(cvNew, item.EquipmentID);//按EquipmentID显示
                        ////加载区域内节点
                        //loadChildInArea(cvNew, comboBoxSys.SelectedValue?.ToString(), item.Id);

                    }
                }
            }
            #endregion

        }



        private void loadChildInAreaFromCache1(System.Windows.Controls.Canvas canvasParent, string SysNo, long blockId)
        {
            if(blockId==16 && SysNo== "D-Ag")
            {

            }
            var sys_name = SysNo;
            //var sys_type = currentSysObj?.OutType;

            ItemsDto<HKP_TakeoffDto> res = lst_takeoff;
            var paidian_dist = numFitDistence.Value * 1000;

            if (res != null && res.result != null)
            {
                jiedian_lst_curr = res.result.items;
                jiedian_lst_curr = jiedian_lst_curr.Where(a => a.BlockId == blockId).ToArray();

                //未指定系统时，不显示接点
                if (!string.IsNullOrEmpty(sys_name))
                {
                    jiedian_lst_curr = jiedian_lst_curr.Where(o => o.SysName == sys_name).ToArray();
                }
                else jiedian_lst_curr = new HKP_TakeoffDto[0];



                //var xcenter = DrawShow.split_arr_col.Average() / 2;
                //var ycenter = DrawShow.split_arr_row.Average() / 2;
                //xcenter += DrawShow.drawEdge_hor;
                //ycenter += DrawShow.drawEdge_ver;

                //当前机台id
                HKP_ToolDto currtool = null;
                if (cbJT.SelectedItem != null) currtool = cbJT.SelectedItem as HKP_ToolDto;


                foreach (HKP_TakeoffDto item in jiedian_lst_curr)
                {
                    //if (item.TakeoffName == "D-Au-L20-E9-4")
                    //{

                    //}
                    var typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "接点" && a.BindDataProperty == item.OutType);
                    if (typeitem == null) typeitem = MyCustomerList.FirstOrDefault(a => a.BindDataType == "接点");

                    //所有接点显示大小相同，因此使用同一个模板  
                    var cv_template_brush = GetShapeJiedian(item.OutType);
                    if (cv_template_brush == null) continue;
                    var cv_template = jiedianui_type_ui[item.OutType];


                    var rtContainer = new System.Windows.Rect((double)item.X, (double)item.Y, cv_template.Width, cv_template.Height);
                    //+边缘距离
                    rtContainer.X += DrawShow.drawEdge_hor;
                    rtContainer.Y += DrawShow.drawEdge_ver;
                    //创建容器,基于父容器，父容器为区域容器.此处不使用相对于区域的坐标。直接加入到初始父级，防止元素超出区域范围不能正常显示。
                    //rtContainer.Offset(-System.Windows.Controls.Canvas.GetLeft(canvasParent), -System.Windows.Controls.Canvas.GetTop(canvasParent));
                    var cvNew = DrawShow.doAddDrawEleContainer_Jiedian(canvasParent, rtContainer);
                    //防止元素超出区域范围不能正常显示。
                    System.Windows.Controls.Panel.SetZIndex(cvNew, int.MaxValue);

                    #region 容器的颜色  已派点的显示为蓝色；未派点可派点的显示为绿色；  
                    //已派点的显示为红色；未派点可派点的显示为绿色；  
                    //机台位置在画布中心 

                    ////未派点的，可派点
                    //var canConnected = lst_jt_sys?.result?.items?.Any(b =>
                    // //b.OutType == item.OutType
                    // b.ToolId.ToString() == currtool?.Id
                    // && !item.Used
                    // && item.Enabled
                    // && Utils.ToInMM(item.OutSize, item.OutSizeUnit) >= Utils.ToInMM(b.OutSize, b.OutSizeUnit) //接点尺寸
                    // && jt_rect.IsVisible((int)((int)item.X + DrawShow.drawEdge_hor), (int)((int)item.Y + DrawShow.drawEdge_ver)) //距离
                    //);

                    ////已派点
                    //var connected = lst_jt_sys?.result?.items?.Any(b =>
                    // //b.OutType == item.OutType
                    // b.ToolId.ToString() == currtool?.Id
                    //&& item.Used
                    ////&& Utils.ToInMM(item.OutSize, item.OutSizeUnit) >= Utils.ToInMM(b.OutSize, b.OutSizeUnit) //流量
                    //&& jt_rect.IsVisible((int)((int)item.X + DrawShow.drawEdge_hor), (int)((int)item.Y + DrawShow.drawEdge_ver))//距离
                    //);
                    if (!item.Used)
                    {
                        jiedian_canp.Add(item);
                        cvNew.Background = brush_paidian_touse;
                    }
                    else
                    {
                        cvNew.Background = brush_paidian_blue;
                    }

                    #endregion


                    //使用模板作为背景展示图形  
                    var cvbg = DrawShow.doAddBgCanvas(cvNew);
                    cvbg.Background = cv_template_brush;


                    //列表转化
                    item.BlockName = lst_block.result?.items?.FirstOrDefault(a => a.Id == item.BlockId)?.BlockName;
                    item.SubmainName = lst_guandao.result?.items?.FirstOrDefault(a => a.Id == item.SubmainId)?.SubmainName;
                    cvNew.ToolTip = new UC_Tooltip_Jiedian(item);
                    System.Windows.Controls.ToolTipService.SetShowDuration(cvNew, 10000);
                    cvNew.Data_Jiedian = item;
                    //区域的快捷菜单
                    container_Jiedian_Menu(cvNew, item);
                    //添加文本说明
                    DrawShow.doAddDrawEleContainer_Desc_Jiedian(cvNew, item.TakeoffNo, typeitem.ShowHeight);

                }
            }
        }
        

    }

}
